我正在尝试将一个JSON片段读入knockout.js中的oberservable数组,但是由于某种原因,contactGroup对象的属性从未被设置过,有人能解释为什么会发生这种情况吗?谢谢!
"contactGroups":[
{"id":1,"name":"Test Group","contact":[{"name":"aaaaaa"},{"name":"bbbbbb"}]
}]
self.contactGroups = ko.observableArray([])
$(data.contactGroups).each(function(group){
var temp = new ContactGroup({id: group.id, name: group.name})
$(group.contact).each(function(contact){
var temp_contact = new Contact(contact)
temp.contact.push(temp_contact)
});
self.contactGroups.push(temp);
})
function ContactGroup(data){
var self = this;
self.id = data.id;
self.name = ko.observable(data.name);
self.contact = ko.observableArray([]);
function Contact(){
this.name = ko.observable();
this.email = ko.observable();
this.telephone = ko.observable();
this.mobile = ko.observable();
this.mail_group = ko.observable();
this.comment = ko.observable();
}
self.addContact = function(){
self.contact.push(new Contact);
}
self.removeContact = function(){
self.contact.remove(this);
}
}发布于 2013-07-18 18:27:02
可观察的数组是函数,所以如果你想设置一个可观察的数组,你应该使用self.contactGroups(array);而不是self.contactGroups.push(temp);
self.map = function() {
var groupArr = [];
ko.utils.arrayForEach(this.items(), function(item) {
var temp_contact = new Contact(contact)
temp.contact.push(temp_contact)
groupArr.push(temp)
});
self.contactGroups (groupArr);
}https://stackoverflow.com/questions/17720841
复制相似问题