collection not saving model if passed as property of model
I'm trying to create a Backbone application without using a global collections variable. this is what I mean. Initially, I created a model and added it to a collection like this in a function in my view
this.mymodel = new MyModel();
this.mymodel.addToCollection();
Inside the addToCollection()
function (called on the instance of the model), I added the instance of the model (represented by this
) and then called save on it
addToCollection(){
mycollectionglobalvariable.add(this) //this global collection variable was created on application init
this.save();
}
In the collection, I have it set up to save to localStorage and everything works fine, except that I didn't want to use a global variable for the collection (primarily to make testing easier), so in my main view I pass the collection with the collection property (this implies that I passed the collection to the main view and set it as the this.mycollection property)
this.mymodel = new MyModel(collection: this.mycollection);
Now, in the constructor to that model, I set the collection property
constructor(options){
this.collection = options.collection;
}
and the addToCollection method is now like this
addToCollection(){
this.collection.add(this);
this.save();
}
The result is that the model is getting added to the collection but it is not getting saved. Why doesn't the model get saved when I pass the collection as property of the model?
You can see here in the Backbone docs that it supports passing the collection as a property.
It looks as if you are simply overwriting the constructor. You should probably call through to the default constructor too: Backbone.Model.apply(this, arguments);
.
However take a look at the source code for the model's constructor: http://backbonejs.org/docs/backbone.html#section-53. It adds the collection option to the model already, so you can remove your constructor entirely.
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId(this.cidPrefix);
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
Finally, it may have just been a typo, but you should pass the options hash to your model as the second parameter.
this.mymodel = new MyModel({}, {collection: this.mycollection});
Check out this jsfiddle for an example: http://jsfiddle.net/mfze3abg/
链接地址: http://www.djcxy.com/p/67148.html上一篇: 检测图像的旋转度
下一篇: 如果作为模型的属性传递,则不保存模型