使用 Knockout Observable 数组的数据绑定复选框

Data binding Checkboxes using Knockout Observable Arrays

我正在尝试重新实现 Udacity JavaScript 设计模式课程中的学生出勤示例。到目前为止,我已经设法重新创建 table 并使用一些学生数据正确地填充它,但是当我更改复选框值时它会出现,这在模型中没有更新。

比如我显示的时候

    debugVM.studentList()[0].days();

在控制台中,输出显示初始出勤数据而不是复选框的当前状态。可以找到用于此的 JSFiddle here.

index.html

 <table>
  <thead>
    <tr>
      <th>Student</th>
      <!-- ko foreach: attendance -->
      <th data-bind="html: $data"></th>
      <!-- /ko -->
    </tr>
  </thead>
  <tbody data-bind="foreach: studentList">
    <tr>
      <td data-bind="html: name, click: $parent.debugStudent"></td>
      <!-- ko foreach: days -->
      <td>
      <input type="checkbox" data-bind="value: $data, checkedValue: $data, checked: $data" />
      </td>
      <!-- /ko -->
    </tr>
  </tbody>
</table>

app.js

var Student = function(student){

  this.name = ko.observable(student.name);
  this.days = ko.observableArray(student.days);
};


var ViewModel = function() {
  var self = this;

  this.attendance = ko.observableArray([1,2,3,4,5,6,7,8,9,10,11,12]);
  this.studentList = ko.observableArray([]);

  students.forEach(function(student) {
    self.studentList.push(new Student(student));
  });

  self.debugStudent = function() {
    console.log(self.studentList()[0].days());
  };
};
var debugVM = new ViewModel();

ko.applyBindings(debugVM);

来自淘汰赛documentation

Key point: An observableArray tracks which objects are in the array, not the state of those objects

在你的例子中,这意味着 days 应该不是可观察数组,而是可观察数组。

例如你可以添加新的viewModel Day:

var Day = function(isChecked) {
    this.isChecked = ko.observable(isChecked);
}

然后像这样设置 days 属性

this.days = [];
for (var i = 0; i< student.days.length; i++) {
   this.days.push(new Day(student.days[i] == 1));
}

working fiddle