2011-09-02 158 views
25

是否可以在模型中嵌套集合?骨干 - 嵌套在模型中的集合

我知道你可以在模型的初始化回调中创建新的集合,并创建可以在集合和父模型之间来回传递的引用。但是,它可以设置集合作为模型的一部分,使得其出口的JSON看起来是这样的:

{ 
    blah: 'blah', 
    myCollection: [ 
     { 
     foo: 'asdf', 
     bar: 'qwer' 
     }, 
     { 
     foo: 'asdf123', 
     bar: 'qwer123' 
     } 
    ] 
} 

如果没有,你是如何处理同步与相关收藏到后端模式?你是否需要挖掘骨干的同步并重建JSON或者是否有更多的无缝?

对不起,如果这个问题已经在其他地方回答。我环顾四周,看到了一些解决方法,但没有什么能真正回答我所寻找的。

回答

30

有两种方法。首先是定义一个获取一切的根模型。你可以覆盖它的parse()方法来为嵌套属性创建子集合和子模型,并覆盖toJSON()方法以转换回适合保存到服务器的JSON结构。

对于小的子集合,这是完全可以接受的。它需要一些编程,但是如果你可以阅读Backbone源代码,怎么做它应该是,不是很明显,但至少可以理解。

或者您可以使用Backbone Relational,它为您完成所有工作。

7

雷纳托接近,但“有”和“设置”将不可用。我相信Reckoner指出了这一点。此外,您将需要从响应中删除属性,否则它将覆盖默认值。

_.extend(Backbone.Model.prototype, { 
    parse: function(resp, xhr) { 
     var attr, model, models, collection, options; 
     for (var prop in resp) { 
      if (this.defaults && this.defaults[prop]) { 
       attr = this.defaults[prop]; 
       if (attr instanceof Backbone.Model) { 
        model = attr.clone(); 
        model.set(resp[prop]); 
        resp[prop] = model; 
       } else if (attr instanceof Backbone.Collection) { 
        models = attr.map(function (model) { return model.clone(); }); 
        options = _.clone(attr.options); 
        collection = new attr.constructor(models, options); 
        collection.add(resp[prop]); 
        resp[prop] = collection; 
       } 
      } 
     } 
     return resp; 
    } 
}); 

希望能帮助别人。