2012-12-14 106 views
1

我有一个主视图模型中包含多个视图模型。我试图插入一个项目到viewmodel B viewmodel A中的数组中。在我的日志中,我看到项目被添加到数组中但它不更新UI。Knockout observableArray不更新多视图模型

http://jsfiddle.net/U7rXA/

----- HTML

<form data-bind="submit: RolesVM.addRole"> 
    <select name="app" data-bind="options:ApplicationsVM.applications,optionsText:'name', value: RolesVM.application"><option></option></select></td> 
    <input data-bind='value: RolesVM.role, valueUpdate: "afterkeydown"'/> 
    <button>Add Role</button> 
</form> 

<ul data-bind="foreach: ApplicationsVM.applications"> 
    <span data-bind="text:name"></span> 
    <ul data-bind="foreach: roles"> 
     <li data-bind="text:name"></li> 
    </ul> 
</ul> 

----- JS

 function MasterVM(applicationsVM, rolesVM) { 
     this.ApplicationsVM = applicationsVM; 
     this.RolesVM = rolesVM; 
    } 
    function ApplicationsVM() { 
     var self = this; 
     self.applications = ko.observableArray([]); 

     self.Populate = function() { 
      var allData = jQuery.parseJSON('[{ "name": "app 1", "roles": [{ "name": "role 1" }] }, { "name": "app 2", "roles": [{ "name": "role 1" }] }]'); 
      var mappedApplications = $.map(allData, function (item) {return new Application(item);}); 
      self.applications(mappedApplications); 
     }; 
    } 
    function RolesVM() { 
     var self = this; 
     self.application = ko.observable(); 
     self.role = ko.observable(); 

     self.addRole = function() { 
      self.application().roles().push(self.role()); 
      console.log(self.application().roles()); 
     }; 
    } 

    function Application(data) { 
     this.name = data.name; 
     this.roles = ko.observableArray($.map(data.roles, function(item) { return new Role(item.name); })); 
    } 

    function Role(data) { 
     this.name = data; 
    } 

    var applicationsVM = new ApplicationsVM(); 
    applicationsVM.Populate(); 
    var rolesVM = new RolesVM(); 
    ko.applyBindings(new MasterVM(applicationsVM, rolesVM)); 

回答

4

您将要直接调用push对observableArray而不是底层阵列。这是通知任何用户它已经改变了。所以,你会婉做:

self.application().roles.push(self.role()); 

而不是:

self.application().roles().push(self.role()); 
+0

的更新我的UI,但该项目回来为“结果”不管我型。 http://jsfiddle.net/SBkxw/ – Boone

+0

啊,我需要将其设置为一个角色,而不是只是名称的字符串值.. var role = new Role(self.role()); self.application()。roles.push(role); – Boone

+0

这是一个重要的观点,感谢帮助解决了我的问题! 我删除了()并解决。我使用像这样ko.utils.arrayPushAll(arr,itemModels); – Umair