Search code examples
backbone.js

Why is my view duplicating the collection I am passing in backbone.js?


I am just starting to learn Backbone.js and I am creating a couple simple example fiddles for reference. I found a simple JSON api that will return a list of users. The JSON response has some metadata and an array of three users. After binding my collection to my view I am left with 3 extra sets of users.

JS Fiddle

row_template = "<tr>" +
  "<td class='id'></td>" + 
  "<td class='first_name'></td>" +
  "<td class='last_name'></td>" +
  "<td><img class='avatar'></td>"+
  "</tr>"

var UsersView = Backbone.View.extend({
  row_template: row_template,

  initialize: function(options) {
    this.factory = new Backbone.CollectionBinder.ElManagerFactory(this.row_template, this.bindings);
    this.listenTo(options.collection, 'add', this.render);
  },

  render: function () {
    var data = this.collection;
    new Backbone.CollectionBinder(this.factory).bind(data, $('#' + this.el.id + ' table tbody'));
  },

  bindings: {
    first_name: {selector: '.first_name', elAttribute: 'text'},
    last_name: {selector: '.last_name', elAttribute: 'text'},
    avatar: {selector: '.avatar', elAttribute: 'src'},
    id: {selector: '.id', elAttribute: 'text'}
  }
});

var UsersCollection = Backbone.Collection.extend({
  url: 'https://reqres.in/api/users',
  parse: function(response) {
    return response.data;
  }
});

users = new UsersCollection();
users.fetch()

var UsersView = new UsersView({
  el: $('#UsersHolder'),
  collection: users
});


UsersView.render();

Solution

  • The collection event 'add' is emitted for each model in the collection. Since you have three models in your collection, the render function is getting called 3 times, one for each model.

    Solution

    Replace 'add' with 'update' which gets triggered only once for any change to the collection, regardless of the number of models.

    this.listenTo(options.collection, 'update', this.render);