KnockoutJS - unshift() Method



Description

The KnockoutJS Observable unshift('value') method inserts a new item at the beginning of the array.

Syntax

arrayName.unshift('value')

Parameters

Accepts one parameter, that is the value to be inserted.

Example

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray unshift 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 unshift() method.</p>
      <p>Enter name: <input data-bind='value: empName' /></p>
      <button data-bind="click: unshiftEmp">Add Emp in Beginning</button><br><br>
      <p>Array of employees: <span data-bind="text: empArray()" ></span></p>

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

            this.unshiftEmp = function() {
            
               if (this.empName() != "") {
                  this.empArray.unshift(this.empName());   // insert at the beginning
                  this.empName("");
               }
            }.bind(this);
         }
      
         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in array-unshift.htm file.

  • Open this HTML file in a browser.

  • Enter name as Tom and click the Add Emp in Beginning button.

knockoutjs_observables.htm
Advertisements