I have an object that's also saved in the server and I'm creating a Backbone model from that object.
But when I save the model, it's doing a PUT request, which is not what I want. How to tell Backbone that the data is already in the server without doing a fetch?
Backbone determines the newness of a model by checking if an id is set :
isNew
model.isNew()
Has this model been saved to the server yet? If the model does not yet have an
id
, it is considered to be new.
And when you save a model,
And as noted by @JayC in the comments :
If there's an issue that the id can't literally be id
, you can use idAttribute
to say which is the "identity" or key field.
Adding my two cents here, hope it avoids some hair pulling I had to do.
Setting a model's id property directly via constructor to false or null won't do the trick, you have to actually remove it from memory via via delete
For example, I just struggled to copy attributes from one model type to another type as a new model:
copy = Trip.clone()
#doesn't unset the id attribute
schedule = new models.Schedule(_.extend(copy.attributes, {id:null, trip_id:id})
#does unset the id attribute
delete schedule.id
schedule.save null, success: =>
# back from POST vs PUT
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.