I have an application which consists of a Backbone.js collection and real-time connection to the server.
Every time any client adds / removes / updates a model in the collection, the updated collection is broadcasted to all other clients (not the delta; the whole collection).
When handling this update event from the other clients, the only way I've found of updating the collection is a reset(). Unfortunately, this wipes the old models and creates new ones, along with all the view-related side-effects.
Is there a Backbone-sanctioned way of updating a collection that maintains and updates the original models (comparing by id), creating / deleting them only if necessary?
UPDATE Backbone has added the Collection.set method, which is capable of updating existing models.
The solution I went with is:
Backbone.Collection.prototype.update = function(colIn){
var ids = [];
_(colIn).each(function(modIn){
var existing = this.get(modIn);
// update existing models
if (existing) { existing.set(modIn); }
// add the new ones
else { this.add(modIn); }
ids.push(modIn.id);
}, this);
// remove missing models (optional)
var toRemove = this.reject(function(model){
return _(ids).include(model.id);
});
this.remove(toRemove);
return this;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With