Knockout无法手动正确映射

时间:2013-07-18 10:23:45

标签: javascript jquery knockout.js

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

1 个答案:

答案 0 :(得分:0)

可观察数组是函数,因此如果要设置可观察数组,则应使用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);
  }