我需要在初始化时将一个值从视图传递给集合中的每个模型。
在集合之前,我们可以在 Backbone.Collection 构造函数中使用"选项"传递。
在此之后,是否有任何技术可以将一些"选项"传递给集合中的每个模型?
var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
},
initialize: function (attributes, options) {
//Need the some_imp_value accessible here
},
});
var Album = Backbone.Collection.extend({
model: Song
initialize: function (models, options) {
this.some_imp_value = option.some_imp_value;
}
});
您可以重写"_prepareModel"方法。
var Album = Backbone.Collection.extend({
model: Song
initialize: function (models, options) {
this.some_imp_value = option.some_imp_value;
},
_prepareModel: function (model, options) {
if (!(model instanceof Song)) {
model.some_imp_value = this.some_imp_value;
}
return Backbone.Collection.prototype._prepareModel.call(this, model, options);
}
});
现在,您可以在"初始化"中查看传递给模型的属性,您将获得some_imp_value,然后您可以根据需要在模型上进行设置。
虽然它似乎没有文档,但我发现至少在最新版本的 backbone (v1.3.3) 中,传递给集合的选项对象会传递给每个子模型,扩展到集合生成的其他选项项中。我没有花时间确认旧版本是否如此。
例:
var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
},
initialize: function (attributes, options) {
//passed through options
this.some_imp_value = options.some_imp_value
//accessing parent collection assigned attributes
this.some_other_value = this.collection.some_other_value
},
});
var Album = Backbone.Collection.extend({
model: Song
initialize: function (models, options) {
this.some_other_value = "some other value!";
}
});
var myAlbum = new Album([array,of,models],{some_imp_value:"THIS IS THE VALUE"});
注意:我不确定选项对象是否传递给后续的 Collection.add 事件