问题:我让 Json 从服务器返回。Json 是一系列业务,其中每个业务可以有多个联系人。我还想让联系人成为一个可观察的数组,以便绑定到联系人的 html 元素在删除时得到更新,而数组在编辑时得到更新。
我已经设置了以下 jsFiddle - http://jsfiddle.net/rdotlee/GCwjX/1/。
这是我来自 jsFiddle 的视图模型。
var businessViewModel =
{
allBusinesses: ko.observableArray([
{ name: "Biz1", id: 1, Contacts: [{ name: "Joe", email: "test@test", phone: "555-111-1111" }, { name: "Smith", email: "smith@test", phone: "777-111-2223"}] },
{ name: "Biz2", id: 2, Contacts: [{ name: "Joe", email: "test@test", phone: "555-222-1111" }, { name: "Smith", email: "smith@test", phone: "555-111-2222"}] }
]),
businessId: ko.observable(1)
};
businessViewModel.selectedBusiness = ko.dependentObservable(function () {
var biz = this.allBusinesses()[0];
for (var i = 0; i < this.allBusinesses().length; i++) {
if (this.allBusinesses()[i].id == this.businessId()) {
biz = this.allBusinesses()[i];
break;
}
}
return biz;
}, businessViewModel);
businessViewModel.removeContact = function (contact) {
ko.utils.arrayRemoveItem(this.selectedBusiness().Contacts, contact);
ko.applyBindings(businessViewModel, $("#sectionBusinesses")[0]);
} .bind(businessViewModel);
做我需要的最干净/推荐的方法是什么?
谢谢,