2012-09-22 53 views
0

總之一個複雜的集合我要讓其他收藏品和模型創建backbonejs

的結構是這樣的

[{ 
    mainCategory: "Something" 
    subCategories: [ 
     { 
      category: "SomethgingElse", 
      labs: [ 
      { 
       id: 1, 
       title: "Title", 
       description : "Lorem ipsum dolor sit amet" 
       availablelanguages: ["fr","en"] 
      }, 
      { 
       id: 2, 
       title: "Another Title", 
       description : "Lorem ipsum dolor sit amet", 
       availablelanguages: ["fr","en"] 
      }] 
     }, 
     { 
      category: "Testing", 
      labs: [ 
      { 
       id: 1, 
       title: "ZZZZ", 
       description : "Lorem ipsum dolor sit amet" 
       availablelanguages: ["ar","en"] 
      }, 
      { 
       id: 2, 
       title: "VVVVV", 
       description : "Lorem ipsum dolor sit amet", 
       availablelanguages: ["ar","en"] 
      }] 
     } 

    ] 
}] 

我定義的一些收藏品和模型,如以下

的骨幹深具珍藏
var Item = Backbone.Model.extend({ 
    defaults: { 
     title : '', 
     description: '', 
     availableLangagues : [] 
    } 
}); 
var Items = Backbone.Collection.extend({ 
    model: Item 
}); 

var Category = Backbone.Model.extend({ 
    defaults: { 
     categoryName: '', 
     labsList: new Items() 
    } 
}); 
var Categories = Backbone.Collection.extend({ 
    model: Category 
}); 
var TopCategory = Backbone.Model.extend({ 
    defaults: { 
     topCategory: "", 
     categories: new Categories() 
    } 
}); 
var TopCategories = Backbone.Collection.extend({ 
    model: TopCategory 
}); 

我的問題在這裏我要呼籲TopicCategories我想填充一切fetch,將fetch無線會返回一個JSON比如上例中通過,但如果我上TopCategoriesfetch它會返回數據,但就像我在默認

回答

2

你想要做什麼想要的陣列將只是普通的JavaScript數組不是骨幹集合正在利用您的頂級車型的parse()功能。在這個修改後的解析中,你所做的是從你的響應中挑出不同的對象/數組,並將它們轉換爲你想要的集合。示例:TopCategory模型中的parse()

parse: function(response) { 

    if (response.subCategories){ 

     if (!this.subCategories) { 
      this.subCategories = new Categories(response.subCategories); 
     } else { 
      this.subCategories.reset(response.subCategories); 
     } 

     delete response.subCategories; 
    } 

    return response; 
} 

你就能做對具有某種骨幹收集要分析出每個父模型解析定義這種模式。

此鏈接可能會給你一些更多的想法,如何這一切工作。

Dealing with nested collections