gpt4 book ai didi

javascript - 嵌套模板的 KnockoutJS 绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 18:24:32 25 4
gpt4 key购买 nike

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

例如,如果我在 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());

以及 View 的以下内容:

<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 的绑定(bind),它将为添加的 writeup 吐出 empWuItem 模板。这看起来效率很低,因为绑定(bind)应该在 WriteUp 添加到 UserModel 中的 writeups 可观察数组时触发,而不必“重新分配” View 模型中的 selectedUser 属性。

最佳答案

Push 是可观察数组的一个属性:

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

应该是

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

关于javascript - 嵌套模板的 KnockoutJS 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com