Knockout observableArray不使用多个视图模型进行更新

时间:2012-12-14 23:03:29

标签: javascript knockout.js

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

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));

1 个答案:

答案 0 :(得分:4)

您需要直接在observableArray上调用push而不是底层数组。这是通知任何订户它已经改变的原因。所以,你会想做:

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

而不是:

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