问题
I would like to unset() the _id attribute from an instance of a model, to make a POST request using the save() model method.
But i get a Uncaught TypeError: Object [object Object] has no method 'call' backbone-min.js because of this line:
myModel.unset('_id');
I am using idAttribute: "_id" so i tried:
myModel.unset('id');
But it doesn't unset the _id attribute.
回答1:
Using model.unset('_id') should work fine. My guess is that the error is thrown by a change event listener, either in your code or some library code. In order to not trigger events you can use the silent:true option.
However, if you simply want to force the model.save() method to perform a POST, you don't need to unset the _id attribute.
Instead override the model.isNew method. Backbone uses this to determine whether a model is new (and should be POSTed) or existing (and should be PUT). Overriding the method to always return true will make your model to be POSTed every time:
isNew: function() { return true; }
回答2:
Backbone stores the attributes in an object called attributes within the model. The attribute _id, although representative of the ID of that model is not what is used to determine whether a model is new.
There is a property called id (sibling of attributes) which is what is used to make the isNew() determination.
If you want to force a POST, you'll need to delete the id property:
var id = model.id;
model.unset('_id');
delete model.id;
model.save(); // this will do a POST
来源:https://stackoverflow.com/questions/14637156/how-to-unset-an-id-backbone-model-attribute