如何在Backbone.js中的模型中存储对Collection的引用?

时间:2012-12-27 19:46:21

标签: backbone.js

创建新集合时(选择)我想在其上设置一个属性(例如:_question),该属性链接回包含的模型(MultipleChoiceQuestion)

2 个答案:

答案 0 :(得分:2)

这花了我相当多的时间来弄清楚,所以如果将来有人有这个问题......这就是我最后编写的代码。

我发现,与Model不同,Collection的initialize()函数接受2个参数。第一个是models(可以使用初始化集合的模型列表)。第二个是options(你想要的)。有一段时间我的收藏开始时有1个模型,我无法找出原因。事实证明我将options传递到models字段。

包含模型:

m.MultipleChoiceQuestion = Backbone.Model.extend({
    initialize: function(){
        //NULL as first parameter because we don't want models
        this.choices = new c.Choices(null, { 
            _question: this //this is referring to current question
        }); //choices Collection is this
    }
});

收集

c.Choices = Backbone.Collection.extend({
    initialize: function(models, options){
        this._question = options._question;
    },
    model: m.Choice
});

答案 1 :(得分:0)

我实际上发现,尽管我的第一个答案在技术上有效,但是有一个插件可以在模型中存储集合(并创建适当的One-> Many,One-> One和Many-> One relationship

https://github.com/PaulUithol/Backbone-relational

使用该插件将父问题存储为ATTRIBUTE

m.MultipleChoiceQuestion = Backbone.RelationalModel.extend({
    relations: [{
        type: Backbone.HasMany,
        key: 'choices', //says to store the collection in the choices attribute
        relatedModel: m.Choice, //knows we are talking about the choices models
        includeInJSON: true, //when we do toJSON() on the Question we want to show serialize the choices fully
        reverseRelation: {
            key: 'question', //in the CHOICE object there will be an attribute called question which contains a reference to the question 
            includeInJSON: false //when we do .toJSON on a CHOICE we don't want to show the question object (or maybe we want to show the ID property in which case we set it to "id")
        }
    }],
    coolFunction: function () {
        this.get('choices').each(function(choice){
            choice.doSomethingChoicey();
        });
    }
});

所以现在如果我们在选择模型中,我们可以完全引用父问题中的任何内容:

m.Choice = m.RelationalModel.extend({
    coolFunction: function(){
        this.get('question').doSomemethingQuestiony();
        var question_numer = this.get('question').get('question_number');
    }
});