1

我在一个主视图模型中包含多个视图模型。我正在尝试从视图模型 B 将一个项目插入到视图模型 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));
4

1 回答 1

4

您将希望push直接调用 observableArray 而不是底层数组。这就是通知任何订阅者它已更改的内容。所以,你会想做:

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

而不是:

self.application().roles().push(self.role());
于 2012-12-14T23:26:29.993 回答