Sahat Yalkabov
Sahat Yalkabov

Reputation: 33684

Backbone: Many small requests for model changes vs one collection sync?

What is a general good practice for when some action - changes multiple models in Backbone.js:

  1. Trigger multiple PUT requests for each mode.save()
  2. Single request to sync the entire collection

Upvotes: 0

Views: 121

Answers (3)

Bart
Bart

Reputation: 6814

I like the first option, but I'd recommend you implement a PATCH behavior (only send updated attributes) to keep the requests as small as possible. This method gives you a more native "auto-save" feel like Google Docs. Of course, this all depends on your app and what you are doing.

Upvotes: 1

mor
mor

Reputation: 2313

Usually, good REST api practice seems to suggest that you should update, save, create, delete single instances of persistent elements. In fact, you will find that a Backbone.Collection object does not implement these methods.

Also, if you use a standard URI scheme for your data access point, you will notice that a collection does not have a unique id.

GET  /models       //to get all items,
GET  /models/:id   //to read an element,
PUT  /models/:id   //to update an element,
POST /models/:id   //to create an element,
DELETE /models/:id //to delete an element.

If you need to update every model of a collection on the server at once, maybe you need to ask why and there might be some re-thinking of the model structure. Maybe there should be a separate model holding that common information.

As suggested by Bart, you could implement a PATCH method to update only changed attributes of a particular element, thus saving bandwidth.

Upvotes: 1

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14255

In case if the quantity of the changed models greater than 1 - definitely it should be the second item.

Upvotes: 2

Related Questions