11
votes

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.

3

3 Answers

9
votes

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;
};
0
votes

when you add a model to collection then 'add' callback is invoked. Make use of that instead of reset.

0
votes

You can extend collection's add method and check there for model existance