有以下viewmodel:
Config.User = function (data) {
var self = this;
self.username = ko.observable();
self.password = ko.observable();
if (data !== undefined) {
self.username(data.Username);
self.password(data.Password);
}
};
Config.Merchant = function (data) {
var self = this;
// Underlying data
self.id = ko.observable();
self.name = ko.observable();
self.users = ko.observableArray();
if (data !== undefined) {
self.id(data.Id);
self.name(data.Name);
if (data.Users !== undefined) {
var mappedUsers = $.map(data.Users, function (item) {
return new Config.User(item);
});
self.users(mappedUsers);
}
}
});
};
Config.MerchantsViewModel = function (options) {
var self = this;
// Underlying data
self.merchants = ko.observableArray();
$.getJSON(options.loadMerchantsUrl, function (result) {
if (result !== undefined) {
//Set available merchants
var mappedMerchants = $.map(result, function (item) {
return new Config.Merchant(item);
});
self.merchants(mappedMerchants);
}
});
self.deleteUser = function (user, merchant, viewmodel) {
$.post(options.saveMerchantUrl, merchant, function (result) {
if (result.success == true) {
merchant.users.remove(user);
}
else {
//TODO
}
});
};
}
Html就是:
<div data-bind="foreach: merchants(), visible: merchants().length > 0">
<div>
<label>Merchant Id :</label><input data-bind="value: id" />
<label>Merchant Name :</label><input data-bind="value: name"/>
<table>
<tbody data-bind="foreach: users(), visible: users().length > 0">
<tr>
<td>
<a href="#" data-bind="click: function(){$root.deleteUser($data, $parent.users, $root);}"><i class="icon-remove"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
一切似乎都正常工作,除了在js中,来自$ root.deleteUser的$ parent.users正确设置了id和name属性,但users属性是一个包含0个元素的数组。 $ root.deleteUser的$ root也将商家属性设置为0个元素的数组。我不太明白为什么会发生这种情况/