Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ID for a newly saved backbone.js model

Backbone.js makes a POST request when a new model is created and saved, but it doesn't consider the model to be saved (i.e, further saves result in PUTs not POSTs) until the model has an id.. how should the server return the ID of a newly created model so that backbone.js can set it (i.e, how should it respond to the initial POST)?

If backbone.js doesn't handle that, I assume the best way to do it is using the success handler to set the ID?

like image 755
Kim Sun-wu Avatar asked Jan 24 '12 21:01

Kim Sun-wu


1 Answers

You have two options. The first is to return the same JSON structure for a POST request as you would a GET request for the show action (returning a single item.) This uses a single request.

From the documentation:

Set a hash of model attributes, and sync the model to the server. If the server returns an attributes hash that differs, the model's state will be set again.

The other option is to trigger a fetch on your collection after you save. This will take more than 1 request though and will always be less efficient.

like image 151
Gazler Avatar answered Nov 11 '22 13:11

Gazler