背景
我正在开发一个非常基本的应用程序,作为 Knockout 的学习练习。在我的 View 模型中,我有一个可观察的学生
数组。这个对象由许多student
组成,这是我的模型。每个学生都有一个可观察的分数
数组。 scores
数组由动态推送到 scores
数组的可观察数字组成。
以上信息描述了我的意图。不幸的是,有什么东西坏了,但我无法破译出哪里。我的控制台日志显示,当我推送到数组时,分数数组中的值没有被更新。我不清楚我的逻辑/方法哪里错了。当我尝试更新 Scores 数组中的平均分数时,最明显地看到缺乏更新。
我的内容以及控制台日志可以在此处访问:http://jsbin.com/fehoq/45/edit
HTML
<button data-bind="click: addWork">Add New Assignment</button>
<table>
<thead>
<tr>
<th>Name</th>
<!-- ko foreach: assignments -->
<th><input data-bind="value: workName + ' ' + ($index() + 1)"/></th>
<!-- /ko -->
<!--<th data-bind=>Overall Grade</th> -->
<th>Class Grade</th>
</tr>
</thead>
<tbody data-bind="foreach: students">
<tr>
<td><input data-bind="value: fullName"/></td>
<!-- ko foreach: scores -->
<td><input data-bind="value: $data"/></td>
<!-- /ko -->
<td><input data-bind="value: mean" /></td>
<td><input type="button" value="remove" data-bind="click: $root.removeStudent.bind($root)". /></td>
</tr>
</tbody>
</table>
JS
请注意,下面的代码是相关片段,而不是整个应用程序。
1.型号
var StudentModel = (function () {
function StudentModel(fullName) {
var _this = this;
this.fullName = fullName;
this.scores = ko.observableArray();
this.mean = ko.computed(function (scores) {
var n = 0;
ko.utils.arrayForEach(_this.scores(), function (score) {
n += score();
console.log(n);
});
n = n / _this.scores().length;
return n;
});
}
...
2.查看模型
function StudentsViewModel() {
var _this = this;
this.students = ko.observableArray([
new Gradebook.Model.StudentModel("Jeff Smith"),
new Gradebook.Model.StudentModel("Gandalf")
]);
this.assignments = ko.observableArray([
new Gradebook.Model.WorkModel("Math"),
new Gradebook.Model.WorkModel("Reading")
]);
this.addStudent = function () {
this.students.push(new Gradebook.Model.StudentModel(""));
this.updateRows();
};
this.addWork = function () {
this.assignments.push(new Gradebook.Model.WorkModel("Assignment "));
this.updateRows();
};
this.updateRows = function () {
ko.utils.arrayForEach(_this.students(), function (student) {
while (student.scores().length < _this.assignments().length) {
student.scores.push(ko.observable(100));
}
});
};
}
编辑
作为补充说明,我花了相当多的时间在 SO 上研究这个问题,但到目前为止我遇到的解决方案都对我没有帮助。
最佳答案
问题在于,绑定(bind)中的 value: $data
指的是可观察数组条目的展开的、不可观察的值,而不是可观察本身。
本质上,这使其成为一种单向绑定(bind) - 它读取初始状态,然后再也不会更新。
从 Knockout 3.0 开始,您可以使用 $rawData
代替:
<!-- ko foreach: scores -->
<td><input data-bind="value: $rawData"/></td>
<!-- /ko -->
来自 Binding Context 文档:
$rawData
This is the raw view model value in the current context. Usually this will be the same as $data, but if the view model provided to Knockout is wrapped in an observable, $data will be the unwrapped view model, and $rawData will be the observable itself.
引用:Knockout.js using value:
binding in a foreach
over a list of strings - does not update
关于javascript - Knockout JS : Observable Array not updating, 无法确定原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23185081/