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.
});

也许,我认为这是完全错误的,但我希望我已经很好地解释了我的问题,以帮助你帮助我。

4

1 回答 1

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);

所以每个模型都应该直接在 Vocabulary 模型上有一个词集合。

检查小提琴

于 2013-08-22T19:01:07.983 回答