1

在http://jsfiddle.net/gZC5k/1004/慢慢扩展我的嵌套表单我遇到了一个困难,我想用它来计算嵌套 JSON 数组中的子项数量。中断的代码在 // this 中断

    self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
    return {
        firstName: ko.observable(contact.firstName),
        lastName: ko.observable(contact.lastName),
        isKey: ko.observable(contact.isKey),
        gender: ko.observable(contact.gender),
        phones: ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) {
            return {
                type: ko.observable(phone.type),
                number: ko.observable(phone.number),
                calls: ko.observableArray(phone.calls),
                callsVisible: ko.observable(false)
            };
        })),
        addresses: ko.observableArray(contact.addresses),
        optionGender: optionGender,
        phonesVisible: ko.observable(false),
        addressesVisible: ko.observable(false),

// this breaks            
//            numberOfPhones: ko.computed(function (contact) {
//                return contact.phones.length;
//            });
    };
}));

错误在哪里?

4

2 回答 2

1

我认为您需要将每个联系人创建为一个函数:

var ContactModel = function(contact)
{
    var self = this;
            self.firstName = ko.observable(contact.firstName);
            self.lastName = ko.observable(contact.lastName);
            self.isKey = ko.observable(contact.isKey);
            self.gender = ko.observable(contact.gender);
           self. phones = ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) {
                return {
                    type: ko.observable(phone.type),
                    number: ko.observable(phone.number),
                    calls: ko.observableArray(phone.calls),
                    callsVisible: ko.observable(false)
                };
            }));
            self.addresses = ko.observableArray(contact.addresses);
            self.optionGender = optionGender;
            self.phonesVisible = ko.observable(false);
            self.addressesVisible = ko.observable(false);

            self.numberOfPhones = ko.computed(function () {
                return self.phones().length;
            });
        return self;
};

并像这样创建它:

self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
        return new ContactModel(contact);
    }));
于 2013-02-26T14:11:49.793 回答
0

你可以试试这个:

numberOfPhones: ko.computed(function () {
                return contact.phones.length;
     })
于 2013-02-26T15:18:33.293 回答