我正在尝试重新实现 Udacity JavaScript 设计模式类(class)中的学生出勤示例。到目前为止,我已成功重新创建该表并使用一些学生数据正确填充该表,但是当我更改复选框值时,它会出现在模型中未更新的情况。
例如,当我显示时
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);
最佳答案
来自 knockout 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));
}
关于javascript - 使用 Knockout Observable 数组的数据绑定(bind)复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136968/