2013-08-22 146 views
1

我剛剛開始使用Backbone.js,並且遇到了嵌套模型和集合的問題。如何創建嵌套模型和集合(子集合)

對於此示例,我只有一個端點/vocabulary.json

這裏是什麼將返回一個樣本:

[ 
{ 
    "id": 1, 
    "words": [ 
     { 
      "native": "hello", 
      "foreign": "hola" 
     }, 
     { 
      "native": "yes", 
      "foreign": "si" 
     }, 
     { 
      //... More words in this lesson 
     } 
    ] 
}, 
{ 
    //... More lessons coming from this endpoint 
} 
] 

它基本上的lessons集合,每個lesson具有詞彙words的集合。

我怎麼能創建一個words集合,而沒有另一個url端點(集合所要求的,似乎)?

這是我到目前爲止。其實,這是一個精簡的基本版本,因爲我所嘗試的一切都不起作用。

/entities/vocabulary.js

Entities.Vocabulary = Backbone.Model.extend({}); 

Entities.Vocabularies = Backbone.Collection.extend({ 
    model: Entities.Vocabulary, 
    url: "/vocabulary.json" 
}); 

// Here is where I am struggling 

Entities.Vocabulary.Word = Backbone.Model.extend({ 
    // what to do? 
}); 

Entities.Vocabulary.Words = Backbone.Collection.extend({ 
    // what to do? 
    // Need some method to go into the Entities.Vocabularies Collection, pluck a given id 
    // and return the "words" attribute as a new Collection to work from. 
}); 

也許,我想這個完全錯誤的,但我希望我已經解釋了我的問題不夠好,幫你幫我。

回答

1

你幾乎在那裏。您可以在模型上使用parse方法,您可以在其中編寫將單詞集合與詞彙模型相關聯的邏輯。這些行中的內容。

// This would be your main Model 
// Set the idAttribute on it 
// Use the parse method here which hits before initialize 
// where you attach the words collection on each Vocabulary Model 
Entities.Vocabulary = Backbone.Model.extend({ 
    idAttribute : 'id', 
    parse: function (response) { 
     // If theresponse has wods in response 
     // attach it words collection to the Vocabulary Model 
     if (response.words) { 
      this.words = new Entities.Vocabulary.Words(response.words || null, { 
       parse: true 
      }); 
     } 
     // Delete the words object from response as the collection is already 
     // created on the model 
     delete response.words; 

     return response; 
    } 
}); 

// Collection of Vocabulary 
Entities.Vocabularies = Backbone.Collection.extend({ 
    model: Entities.Vocabulary, 
    url: "/vocabulary.json" 
}); 

// This would be the model for Word inside a Specific Vocabulory 
// Associate a idAttribute if it has one. 
// Add a parse method if you have any other extra processing for this model 
Entities.Vocabulary.Word = Backbone.Model.extend({ 

}); 

// Just a Collection of words for the vocabulory 
Entities.Vocabulary.Words = Backbone.Collection.extend({ 

}); 


// Pass the object, and pass in the parse: true 
// parameter so that parse is called before initialize 
var vocabularies = new Entities.Vocabularies(navi, { 
    parse: true 
}); 

// If you want to fetch a new collection again you would just do 

//vocabularies.fetch({parse: true}); 


console.log(mainCollection); 

因此,每個模型應該直接在詞彙模型上有詞彙集合。

Check Fiddle