KnockoutJS - método remove ()

Descripción

El KnockoutJS Observable remove('value') El método elimina los elementos que coinciden con el 'valor' y los devuelve como una matriz.

Sintaxis

arrayName.remove('value')

Parámetros

Acepta un parámetro como valor que se eliminará.

Ejemplo

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray remove method</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Example to demonstrate remove() method.</p>
      <button data-bind = "click: removeEmp">Remove selected Emp</button>
      <p>Array of employees:</p>
      <select multiple = "true" size = "8" data-bind = "options: empArray , 
         selectedOptions: chosenItem"> </select>

      <script>
         function EmployeeModel() {
            this.empName = ko.observable("");
            this.chosenItem = ko.observableArray("");
            this.empArray = ko.observableArray(['Scott','James','Jordan','Lee',
               'RoseMary','Kathie']);

            this.removeEmp = function(chosenItem) {
               
               if (this.chosenItem().length == 0)  {
                  alert("Please select item/s to be removed.");
               }
               
               while(this.chosenItem().length > 0) {
                  this.empArray.remove(this.chosenItem()[0]);
               }
            }
         }

         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

Salida

Realicemos los siguientes pasos para ver cómo funciona el código anterior:

  • Guarde el código anterior en array-remove.htm archivo.

  • Abra este archivo HTML en un navegador.

  • Seleccione el elemento que se eliminará de la lista y haga clic en el botón Eliminar Emp seleccionado.