2012-06-27 31 views
1
我在与Knockout.JS

KnockoutJS绑定和嵌套模板

例如,如果我有以下中的发言权文件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数组时,表不会更新。这是我试图完成的一个简化版本,但是应该假定当他们创建一个文件时,它应该根据新的信息更新这个文件。

我是Knockout的新手,所以任何帮助将不胜感激!

谢谢。

- = - =编辑1 = - = -

有一点需要注意,如果你重装了selectedUser它会吐出所添加的书面记录的empWuItem模板的结合。这看起来效率不高,因为WriteUp被添加到UserModel中的writeups可观察数组而不必在视图模型中“重新分配”selectedUser属性时触发绑定。

回答

2

推的是观察到阵列的属性:

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

应该

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

完美!这很好。谢谢您的帮助。 – Aric