2011-09-02 110 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; 
    } 
}); 

希望能幫助別人。