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?
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.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
Cons
Put the collection's
models
array into a modelCollections 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.Pros
Cons
Collection's
.sync
function is only a proxy toBackbone.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.