如何使用knockout.js添加一个项目或通过单击删除项目

时间:2017-01-28 13:55:34

标签: javascript user-interface knockout.js data-binding

我想通过点击"添加一个项目来添加一个项目"并单击"删除一个项目"删除项目。 我不知道我应该在哪里使用数据绑定,以及如何在代码中添加People数组。请帮我。

这是我的代码:

<div data-bind="foreach: { data: people, as: 'person'}">
<!-- ko foreach: person -->
<div class="item form-collection-group " >
    <div class="title active">
        <span class="accordion-title" data-bind="text : fullName"> title </span>
    </div>
    <div class="content form-collection-content-holder active">               

                    <label class=""> first name </label>
                    <div class="ui input">
                        <input type="text" data-bind="textInput: lastName" >
                    </div>
                    <label class=""> lastName </label>
                    <div class="ui  input">
                        <input  data-bind="textInput: firstName" type="text"  >
                    </div>
    </div>
</div>
<br>
<!-- /ko -->
</div>
<br>
<button>add one field</button>
<button>remove one field</button>

 <script>
 var ViewModel = function() {
 var self = this;
 self.firstName = ko.observable('');
 self.lastName = ko.observable('');
 self.fullName = ko.computed(function() {
    return self["firstName"].call() + " " + self.lastName() + " Title ";
   }, self);
 };

 ko.applyBindings({
    people: [
                     [new ViewModel()] ,[new ViewModel()] 
             ]
 });

 </script>

1 个答案:

答案 0 :(得分:1)

通常在添加和删除您要使用的项目和可观察数组时。 http://knockoutjs.com/documentation/observableArrays.html。添加按钮单击绑定将新项目推送到数组。然后删除按钮将从数组中调用父删除。这是一个工作小提琴。 http://jsfiddle.net/LkqTU/33457/或者您可以运行下面的代码段

function person(firstName, lastName) {
  var self = this;
  this.firstName = ko.observable(firstName);
  this.lastName = ko.observable(lastName);
  this.fullName = ko.pureComputed(function() {
    return self.firstName() + " " + self.lastName();
  }, this);
 

}

function model() {
  var self = this;
  this.firstName = ko.observable('');
  this.lastName = ko.observable('');
  this.people = ko.observableArray();
  this.add = function() {
    self.people.push(new person(self.firstName(), self.lastName()));
  }
  this.remove = function(row) {
    self.people.remove(row);
  }
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-bind="foreach: people">
  Title:
  <span class="accordion-title" data-bind="text : fullName"> </span>
  <button data-bind="click: $parent.remove">X</button>
</div>
<div>
  <input data-bind="textInput: firstName" placeholder="first name" />
  <input data-bind="textInput: lastName" placeholder="last name" />
  <button data-bind="click: add">add</button>
</div>