Backbone.js: add an item to a collection without re-rendering the entire collection

I have a view that derives from the collection:

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

In the view initializer, I bind the add collection event to the view rendering function:

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

elsewhere in the application, I am adding an item to the collection.

 bookSubscription_collection.add(model); 

The problem with this code is that if I add a new item to the collection, then all the elements in the collection will be re-rendered.

Is there a way to add a new item to the collection without reprocessing all the other items, but just visualize the new item?

+8
collections
source share
3 answers

Instead of binding the collection, add the event to the visualization function, bind it to some other function that accepts the added model, and modify the DOM with data from the added model.

+3
source share

This is a simplified version of how I do it. reset adds all models to the user interface, and add adds one model to the user interface. addAll basically has a loop that calls addOne for each model. It can probably be optimized better, but it works quite well.

 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; } 
+4
source share

Abraham wrote a good example. I also used it like that

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

but I think addOne is the best solution

0
source share

All Articles