[英]Backbone.js: Passing value From Collection to each model
I need to pass a value from the view to each models inside a collection, while initializing. 我需要在初始化时将视图中的值传递给集合内的每个模型。
Till Collection we can pass with 'options' in the Backbone.Collection constructor. 直到收集,我们才能在Backbone.Collection构造函数中传递“选项”。
After this, is there any technique where I can pass the some 'options' into each models inside the 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;
}
});
You can override the "_prepareModel" method. 您可以覆盖“ _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);
}
});
Now you can look at the attributes passed to the model in 'initialize' and you'll get some_imp_value, which you can then set on the model as appropriate.. 现在,您可以在“ initialize”中查看传递给模型的属性,您将获得some_imp_value,然后可以在模型上适当地进行设置。
While it appears to be undocumented, I have found that in at least the latest version of backbone (v1.3.3) that the options object passed to a collection gets passed to each child model, extended into the other option items generated by the collection. 尽管它似乎没有记录,但我发现至少在主干的最新版本(v1.3.3)中,传递给集合的options对象传递给每个子模型,并扩展到该集合生成的其他选项中。 I haven't spent the time to confirm if this is the case with older releases.
我没有花时间确认旧版本是否属于这种情况。
Example: 例:
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"});
Note: I am unsure if the options object is passed to subsequent Collection.add events 注意:我不确定选项对象是否传递给后续的Collection.add事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.