In my app, the user creates a collection with a bunch of models. As I don't want to make a ton of requests to the server, I've created a custom function that saves these models in batch to the server. The server then responds with all the models including their id, and this is then set to the various models. All working well so far.
The problem I'm having now is that Backbone doesn't know that at this point all models are synced with the server. So at a later point in the app, when I call model.save() on each model, it sends each model to the server again (which should be only the ones that are changed since the batch operation). How could I let Backbone know that all models are synced? I was looking at the 'changed' and 'hasChanged' attributes, but am not quite sure if I should manipulate these (I guess not).
In my app, the user creates a collection with a bunch of models. As I don't want to make a ton of requests to the server, I've created a custom function that saves these models in batch to the server. The server then responds with all the models including their id, and this is then set to the various models. All working well so far.
The problem I'm having now is that Backbone doesn't know that at this point all models are synced with the server. So at a later point in the app, when I call model.save() on each model, it sends each model to the server again (which should be only the ones that are changed since the batch operation). How could I let Backbone know that all models are synced? I was looking at the 'changed' and 'hasChanged' attributes, but am not quite sure if I should manipulate these (I guess not).
Share Improve this question asked Dec 1, 2012 at 15:23 BjornBjorn 9041 gold badge10 silver badges29 bronze badges2 Answers
Reset to default 7Backbone does not include the feature of tracking changed attributes since last sync with server.
The changed
and hasChanged
are not dealing with changed attributes since last sync with server.
You will have to create your own mechanism for tracking the state of your models:
- Each model should have a
hasChangedSinceLastSync
flag. - Each model should bind (.on) to it's own
change
event and set the flag to true. - Override the
sync
method and set the flag to false once data is returned from the server (for read/create/update).
Backbone will make a HTTP POST
to create your model server-side if the id
attribute of you model is unset/null.
So what you should do is set this id
attribute manually when the server returns them.
Also, if your id
attribute is not id
, you can tell backbone that it's another attribue.
Cf, the docs :
- Manually set an attribute : http://backbonejs/#Model-set
- The id attribute of your model : http://backbonejs/#Model-id
- Reference to the sync method that is being called under the sheets when you
save()
a model : http://backbonejs/#Sync