我刚刚开始使用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.
});
也许,我在考虑这个完全错误,但我希望我能够很好地解释我的问题,以帮助你帮助我。
答案 0 :(得分: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 强>