Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js: add an element to a collection without re-rendering all the collection

I have a view that render itself from a Collection:

render: function() {

    $(this.el).html(JST['templates/menu']({collection: this.collection }));
    $('#nav').html(this.el);     
}

In the view initializer, i bind the add event of the collection on the render function of the view:

initialize: function() {
    this.render();
    var self = this;
    this.collection.bind("add", function(event){
        self.render();
    });
}

elsewhere in the application, I add an item to the collection.

bookSubscription_collection.add(model);

The problem with that code is, if I add a new item to the collection, then all the items in the collection are re-rendered.

Is there a way to add a new item to a collection without re-render all the other items, but just render the new item?

like image 228
Jonathan Aubuchon Avatar asked Feb 15 '12 02:02

Jonathan Aubuchon


1 Answers

This a simplified version of how I'm doing it. reset adds all the models to the UI and add adds a single model to the UI. addAll basically has a loop that calls addOne for each model. It could probably be optimized better but it works well enough.

initialize: function() {
    _.bindAll(this, 'render', 'addOne', 'addAll');

    leads.bind('add', this.addOne, this);
    leads.bind('reset', this.addAll, this);
  },
  render: function() {
    this.addAll();
    return this;
  },
  addOne: function(model) {
    // add the model to HTML
  },
  addAll: function(options) {
    leads.each(this.addOne);
    return this;
  }
like image 192
abraham Avatar answered Sep 29 '22 11:09

abraham