TL DR . If I look at the entire model collection from the server, how can I combine the changed attributes into each model and add / remove added / removed models from the collection?
In my base application, I look through the entire collection of models. I have a Backbone.Collection , which I basically call reset every time I get an array of models, so:
myCollection.reset(server_response);
The only problem is that he gets rid of old models, which eliminates the benefits of events on the model. Of course, this is reset , but I only want to change the changed attributes of the models and delete the models not in the answer and add the models that were in the answer, but not in the collection.
Essentially, I want data fusion.
For models that are already in the answer and in the collection, I believe that I can just make model.set(attributes) , and it takes care of set only those that have actually changed, raising change events in the process. This is great.
But how can I handle cases when the models were in the answer, but not in the collection already, and vice versa, and not in the answer, but in the collection?
My suggestion
I don’t know if the backbone already has a way to do this, and I can be excessive, and that’s why I ask, but then I was thinking of creating a method in my collection that gets server_response .
It will receive all id attributes of server_response and all id attributes of models already in the collection.
The difference in id in the answer - collection = models will be added, and vice versa, models will be deleted. Add and remove these models from the collection.
The intersection of both sets of id would be modified models, so iterate through these id and just do a collection.get(id).set(attributes) .
In pseudocoding:
merge: (server_response) => response_ids = _.pluck(server_response, 'id') collection_ids = @pluck('id') added = _.difference(response_ids, collection_ids) for add in added @add(_.find(server_response, (model) -> return model.id == add )) removed = _.difference(collection_ids, response_ids) for remove in removed @remove(@get(remove)) changed = _.intersection(response_ids, collection_ids) for change in changed @get(change).set(_.find(server_response, (model) -> return model.id == change ))