可观察数组,其中数组中的每个项都包含一个数组 - 如何使内部数组可观察

时间:2012-09-07 03:37:19

标签: knockout.js

问题:我让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);

什么是最干净/推荐的做我需要的方法?

谢谢,

1 个答案:

答案 0 :(得分:1)

首先,我不确定为什么每次删除联系人时都会调用ko.applyBindings。你通常只想调用一次applyBindings,这通常会导致问题。

我建议使用ko.mapping插件,这将使整个过程相当轻松。

我还更新了你的removeContact以使用更新的ViewModel,并且稍微更改了你的selectedBusiness。

这是小提琴:http://jsfiddle.net/GCwjX/5/ 和代码:

var jsonData = {
    allBusinesses: [{
        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"}]}]
};
var businessViewModel = {
    allBusinesses: ko.observableArray(),
    businessId: ko.observable(1)
};

businessViewModel.selectedBusiness = ko.dependentObservable(function() {
    var biz = this.allBusinesses()[0];
    biz = ko.utils.arrayFirst(this.allBusinesses(), function(item) { 
        return (item.id() === parseInt(this.businessId())); 
    }, this);
    return biz;
}, businessViewModel);

businessViewModel.removeContact = function(contact) {
    this.selectedBusiness().Contacts.remove(contact);
}.bind(businessViewModel);

ko.mapping.fromJS(jsonData, {}, businessViewModel);
ko.applyBindings(businessViewModel);​