how to unset an _id backbone model attribute?

旧时模样 提交于 2019-12-13 06:00:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!