我在一个主视图模型中包含多个视图模型。我正在尝试从视图模型 B 将一个项目插入到视图模型 A 的数组中。在我的日志中,我看到该项目被添加到数组中,但它没有更新 UI。
-----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));