Backbone.js: Passing value From Collection to each model
backbone-relational, backbone.js, javascript
Solution
You can override the "_prepareModel" method.
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..
Problem
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. 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; } }); ```