-->

Sync collection changes with the backend

2019-03-04 12:47发布

问题:

I use Backbone.js and I have a collections of models. This collection is retrieved and displayed on the front-end. On the front-end, I want the user to remove and add new models to the collection.

When the user is finished and he clicked "save", I want the entire collection to be updated. Meaning that when clicking 'save', the collection is synced (somehow). Added models are saved and removed models are deleted.

If I manipulate the collection by removing and adding models, and then use ex:

this.collection.sync()

Will it remove and add models?

回答1:

There are at least 2 ways to achieve this.

Make an API endpoint to manage the models

When adding/updating a model, save the model directly with .save and when a model is removed, call .destroy on it.

The collection also has a .create function which adds the new model to it and saves it at the same time.

Best thing to do everything in one request.

Not always. The collection could be big and the changes rather small, so exchanging 100 objects with the server each time instead of X small requests to add, delete or update a model within the list.

Pros

  • Reusable endpoints to manage individual models
  • Light data transfer, faster than sending the whole collection (only changes are sent through partial updates)
  • Possible custom behaviour for each action
  • Easy real-time update implementation

Cons

  • More requests when doing a lot of changes
  • Needs models to have ids
  • Additional endpoints to manage
  • Not meant for bulk operations (save all models at once)

Put the collection's models array into a model

Collections are not meant to be saved. Instead, put the models of the collection into a model which communicates with an API endpoint. This endpoint should expect an object with an array field, which can serve to replace the collection server-side.

var CollectionModel = Backbone.Model.extend({
    urlRoot: "collection/endpoint/"
});

var myModel = new CollectionModel();

// ...sometime later...

myModel.save({
    arrayAttribute: yourCollection.toJSON()
}, { patch: true });

Pros

  • One endpoint; always the same call to the API
  • Easy to implement; just in one place where the save occurs

Cons

  • All models are transferred on every request regardless of changes
  • Could be slow if the collection is big

Collection's .sync function is only a proxy to Backbone.sync and do nothing without the correct parameters. It is only used internally within .fetch (line 1055) and isn't meant to be used directly, unless adding a custom behavior.