Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a Backbone.js collection without wiping old models

Tags:

backbone.js

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.

like image 428
Brennan Roberts Avatar asked Aug 17 '11 18:08

Brennan Roberts


1 Answers

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;
};
like image 186
Brennan Roberts Avatar answered Jan 03 '23 12:01

Brennan Roberts