慢慢扩展我的嵌套表单http://jsfiddle.net/gZC5k/1004/我遇到了一个难以开始工作的问题。计算我想用来计算嵌套JSON数组中的子项数。中断的代码是//这个中断
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;
// });
};
}));
错误在哪里?
答案 0 :(得分: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);
}));
答案 1 :(得分:0)
你可以试试这个:
numberOfPhones: ko.computed(function () {
return contact.phones.length;
})