Jonathan Aubuchon
Jonathan Aubuchon

Reputation: 415

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?

Upvotes: 8

Views: 3126

Answers (3)

Michal
Michal

Reputation: 618

abraham wrote a good example. Ive been also using it like this

initialize: ->    
  self = @
  @model.bind "add", (task) ->
    $(self.el).append new app.TaskIndexItemView(model: task).render().el

but i think the addOne is better solution

Upvotes: 0

abraham
abraham

Reputation: 47833

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

Upvotes: 4

Eric Turner
Eric Turner

Reputation: 1824

Instead of binding the collection's add event to the render function, bind it to some other function that accepts the model that was added, and modifies the DOM with data from the model that was added.

Upvotes: 3

Related Questions