【问题标题】:KnockoutJS Bindings With Nested Templates带有嵌套模板的 KnockoutJS 绑定
【发布时间】:2012-06-27 18:51:25
【问题描述】:

我在使用 Knockout.JS 进行嵌套绑定时遇到问题

例如,如果我在 app.js 文件中有以下内容:

var UserModel = function() {
    this.writeups = ko.observableArray([]);
}

var WriteupModel = function() {
    this.type = 'some type';
}

var MyViewModel = function() {
    this.newUser = new UserModel();
    this.selectedUser = ko.observable(this.newUser);

    this.selectedUser().writeups().push(new WriteupModel());
}

ko.applyBindings(new MyViewModel());

以及以下视图:

<div id="empReportView" data-bind="template: { name: 'empTmpl', data: selectedUser }"></div>

<script type="text/html" id="empTmpl">
    <table>
        <tbody data-bind="template: { name: 'empWuItem', foreach: $data.writeups } ">
        </tbody>
    </table>
</script>

<script type="text/html" id="empWuItem">
    <tr>
        <td data-bind="text: type"></td>
    </tr>
</script>

每当另一个 WriteupModel 被推送到属于 selectedUser 的 writeups 数组时,表就不会更新。这是我正在尝试完成的简化版本,但假设当他们创建一个 writeup 时,它应该根据新信息更新 write-ups 表。

我是 Knockout 的新手,因此我们将不胜感激!

谢谢。

-=-= 编辑 1 =-=-

需要注意的一点是,如果您为 selectedUser 重新加载绑定,它将为添加的 writeup 吐出 empWuItem 模板。这似乎效率低下,因为绑定应该在将 WriteUp 添加到 UserModel 中的 writeups 可观察数组时触发,而不必“重新分配”视图模型中的 selectedUser 属性。

【问题讨论】:

    标签: javascript knockout.js knockout-2.0


    【解决方案1】:

    push 是 observable 数组的一个属性:

    this.selectedUser().writeups().push(new WriteupModel())
    

    应该是

    this.selectedUser().writeups.push(new WriteupModel());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2017-03-26
      • 2015-08-29
      • 1970-01-01
      相关资源
      最近更新 更多