Knockoutjs-obs-array-unshift

提供:Dev Guides
移動先:案内検索

KnockoutJS-unshift()メソッド

説明

KnockoutJS Observable * unshift( 'value')*メソッドは、配列の先頭に新しいアイテムを挿入します。

構文

arrayName.unshift('value')

パラメーター

1つのパラメーター、つまり挿入される値を受け入れます。

<!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>

出力

上記のコードがどのように機能するかを確認するために、次の手順を実行してみましょう-

  • 上記のコードを array-unshift ファイルに保存します。
  • このHTMLファイルをブラウザーで開きます。
  • 「Tom」という名前を入力し、「開始時にEmpを追加」ボタンをクリックします。