创建新集合(选择)时,我想在其上设置一个属性(例如:_question),该属性链接回包含模型(MultipleChoiceQuestion)
问问题
820 次
2 回答
2
这花了我很多时间来弄清楚,所以以防将来有人遇到这个问题......这是我最终编写的代码。
我发现,与 Model 不同,Collection 的 initialize() 函数接受 2 个参数。第一个是models
(这是您可以用来初始化集合的模型列表)。第二个是options
(你想要什么)。有一段时间,我的 Collection 最初只有 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
});
于 2012-12-27T19:46:21.423 回答
0
我实际上发现虽然我的第一个答案在技术上有效,但有一个插件可以处理在模型中存储集合(并创建适当的 One->Many、One->One 和 Many->One 关系
https://github.com/PaulUithol/Backbone-relational
使用该插件,您将父问题存储为属性
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');
}
});
于 2013-01-17T16:24:26.710 回答