我在使用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的写入数组上,表都不会更新。这是我正在尝试完成的任务的简化版本,但假设当他们创建一个writeup时,它应该根据新的信息更新writeup表。
我是Knockout的新手,所以任何帮助都将不胜感激!
谢谢。
-=-=编辑1 =-=-
需要注意的一件事是,如果您重新加载selectedUser的绑定,它将为添加的编写内容输出empWuItem模板。这似乎很低效,因为绑定应该在将WriteUp添加到UserModel中的编写可观察数组时触发,而不必在视图模型中“重新分配”selectedUser属性。
发布于 2012-06-28 02:57:40
推送是可观察数组的一个属性:
this.selectedUser().writeups().push(new WriteupModel())应该是
this.selectedUser().writeups.push(new WriteupModel());https://stackoverflow.com/questions/11233097
复制相似问题