Backbone.js集合视图为单个触发器呈现多次

时间:2016-06-23 06:25:25

标签: backbone.js listener backbone-views backbone-events backbone-collections

我有backbone.js集合和collectionview。收集视图收听其集合add事件。但是当我为它的集合添加新模型时,它会为每个模型渲染多次。 请检查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;
  }
});

1 个答案:

答案 0 :(得分:2)

您的render方法呈现整个集合。因此,在添加模型后,您应该清除现有的项目视图:

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

话虽这么说,最好添加一个单独的方法,只是附加单项视图而不是渲染整个集合:

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