Search code examples
backbone.jslistenerbackbone-viewsbackbone-eventsbackbone.js-collections

Backbone.js collection view render multiple times for single trigger


I have backbone.js collection and collectionview. collection view listening to its collection add event. But when I add new models to it's collection it renders mutiple times for each model. Please Check the JSFiddle

var ImageCollectioView = Backbone.View.extend({

  initialize: function() {
    this.collection.bind('add', this.render, this);
  },

  collection: imgColection,
  el: '#cont',
  render: function() {
    var els = [], self = this;
    this.collection.each(function(image){
      var imageView = new ImageView({model: image});
      self.$el.append(imageView.render().el);
    });

    return this;
  }
});

Solution

  • Your render method renders the entire collection. So after adding a model you should clear the existing item views:

     render: function() {
        var els = [], self = this;
        this.$el.empty();
        //------^---- clear existing
        this.collection.each(function(image){
          var imageView = new ImageView({model: image});
          self.$el.append(imageView.render().el);
        });
    
        return this;
    }
    

    That being said, it's better to add a separate method that just appends single item view rather than rendering the entire collection:

    var ImageCollectioView = Backbone.View.extend({
      initialize: function() {
        this.render();
        this.listenTo(this.collection, 'add', this.renderItem);
      },
      el: '#cont',
      render: function() {
        this.collection.each(this.renderItem, this);
        return this;
      },
      renderItem: function(image) {
        var imageView = new ImageView({
          model: image
        });
        this.$el.append(imageView.el);
      }
    });
    

    Updated Fiddle