Reputation: 1973
This is how I currently handle the data passing to my collection's model. But I'm not really sure if this the best/correct way.
MyCollection:
define([ 'underscore', 'backbone','models/mymodel'], function(_, Backbone, myModel){
var MyCollection = Backbone.Collection.extend({
model: function (attr, options){
options.data = {data: options.collection.options.some_data};
return new myModel(attr, options);
},
initialize: function(options) {
this.options = options;
}
});
return MyCollection;
});
MyModel:
define([ 'underscore', 'backbone' ], function(_, Backbone){
var MyModel = Backbone.Model.extend({
defaults: {
},
initialize: function(attr, options) {
` console.log(options.data)
}
});
return MyModel;
});
Is this the only way to pass the data while initializing the collection's model?
Upvotes: 0
Views: 240
Reputation: 33344
You could override how a collection transforms a hash of attributes into a model. It is done via Collection._prepareModel
and you would alter the options passed to this method:
var MyCollection = Backbone.Collection.extend({
model: MyModel,
_prepareModel: function(attrs, options) {
options = _.extend({}, options, {
data: this.options.some_data
});
return Backbone.Collection.prototype._prepareModel.call(this, attrs, options);
},
initialize: function(models, options) {
// note that the options hash is the second argument
this.options = options;
}
});
And a demo http://jsfiddle.net/nikoshr/jd5d8fmy/
Upvotes: 1
Reputation: 1074
No, try this in MyCollection:
model: myModel,
And if you create a new myModel do this:
var model = new myModel({
prop1: 'something', // etc
});
Upvotes: 1