麻烦将表绑定到Knockout集合

时间:2014-01-23 18:15:13

标签: javascript knockout.js

我无法理解为什么这些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>

在这两个表中,前两个文件将显示,但第三个文件不显示。我错过了什么?

2 个答案:

答案 0 :(得分:2)

真的关闭。有两点需要指出:

  1. 状态不是可观察的,您正试图用text: status()打开它。
  2. 您正在将新的FileObject推入一个未包装的数组中,这意味着您完全绕过了可观察数据。将新项目直接推送到可观察数组中,您将获得更好的运气。
  3. 我根据您的原始资料整理了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

请参阅updated fiddle

$(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

});