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;
}
});
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;
}
});
Share
Improve this question
asked Jul 2, 2012 at 16:30
SaneefSaneef
8,9307 gold badges31 silver badges42 bronze badges
2 Answers
Reset to default 6You 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..
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. 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