Issue: I have Json coming back from the server. The Json is an array of businesses where each business can have multiple contacts. I want to make the contacts an observable array also, so that html elements bound to the contacts get updated upon deletion and the array gets updated upon editing.
I've setup the following jsFiddle - http://jsfiddle.net/rdotlee/GCwjX/1/.
Here is my view model from the 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);
What is the cleanest / recommended way to do what I need?
Thanks,