我无法理解为什么这些Knockout表绑定不起作用:
使用Javascript:
$(function () {
var FileObject = function(id, name) {
this.id = id;
this.name = name;
};
var FilesModel = function() {
this.filesSelected = ko.observable(false);
this.myFiles = ko.observableArray([new FileObject(1, 'test_1')]);
this.myFiles.push(new FileObject(2, 'test_2'));
};
var filesModel = new FilesModel();
window.filesModel = filesModel;
ko.applyBindings(filesModel);
filesModel.myFiles().push(new FileObject(3, 'test_3')); // This never shows
alert(filesModel.myFiles().length); // Shows 3 items
});
HTML:
<h3>TABLE 1</h3>
<table>
<tbody data-bind="foreach: myFiles">
<tr>
<td>FILE:</td>
<td data-bind="text: name"></td>
</tr>
</tbody>
</table>
<h3>TABLE 2</h3>
<table>
<tbody data-bind="foreach: myFiles()">
<tr>
<td>FILE:</td>
<td data-bind="text: name"></td>
</tr>
</tbody>
</table>
在这两个表中,前两个文件将显示,但第三个文件不显示。我错过了什么?
答案 0 :(得分:2)
你真的关闭。有两点需要指出:
text: status()
打开它。FileObject
推入一个未包装的数组中,这意味着您完全绕过了可观察数据。将新项目直接推送到可观察数组中,您将获得更好的运气。我根据您的原始资料整理了jsbin example。
具体来说,这个:
filesModel.myFiles().push(new FileObject(3, 'test_3')); // This never shows
应该是:
filesModel.myFiles.push(new FileObject(3, 'test_3')); // Now it does
答案 1 :(得分:1)
在您的HTML中,您尝试数据绑定status()
,但status
不是可观察的。一种方法是让您的FileObject
成员可观察。
此外,您的第三个FileObject
从未显示过,因为您的语法错误。而不是filesModel.myFiles().push
,它应该只是filesModel.myFiles.push
$(function () {
var FileObject = function(id, name, size, status, progress) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.status = ko.observable(status);
};
var FilesModel = function() {
this.filesSelected = ko.observable(false);
this.myFiles = ko.observableArray([new FileObject(1, 'test_1')]);
this.myFiles.push(new FileObject(2, 'test_2', 3, 'status'));
};
var filesModel = new FilesModel();
window.filesModel = filesModel;
ko.applyBindings(filesModel);
filesModel.myFiles.push(new FileObject(3, 'test_3')); // This never shows
alert(filesModel.myFiles().length); // Shows 3 items
});