0

我正在尝试将 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);
        }
    }
4

1 回答 1

0

可观察数组是函数,因此如果要设置可观察数组,则应使用self.contactGroups(array);self.contactGroups.push(temp); 而不是 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);
  }
于 2013-07-18T10:27:02.033 回答