Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-eventsbackbone.js-collections

Change event fired instead reset in backbone view


I'm trying to execute my reset event in view through cllection fetch but it doesn't working...

router:

var tablesCollection = new TablesCollection();
var tablesView = new TablesView({ collection: tablesCollection});
tablesCollection.fetch({ reset: true });

My view:

initialize: function(){

  _.bindAll(this);
  this.collection.bind('reset',   this.render);
  this.collection.bind('add',     this.addTable);
  this.collection.bind('change',  this.changeTable);
  this.collection.bind('destroy', this.delTable);
},
render: function() {
  this.el.innerHTML = _.template( this.template, { data : _.groupBy( this.collection.toJSON(), 'status')} );
}

Change event is still fired also if I have reset: true in fetch. I want to render each item from collection through reset event then through change event just edited one. Thans for any help


Solution

  • Resetting your collection does not remove your event binding. It's just removing the object from the collection.

    If another view/server event start to populate your collection again then your view is still binded and still fire events.

    First of all I would use .on (backbone event system) instead of .bind

    Then if you want to unbind your view from the collection future potential changes use http://backbonejs.org/#Events-off

    Or better, if you want to destroy this specific view (and it's still reacting maybe that's your problem) then use http://backbonejs.org/#View-remove

    It will automatically unbind all your events.

    I hope it helps

    edit:

    reset will always trigger 'change' cause it changes all the object of your collection. You should adapt your render function to be triggered on 'change' instead of 'reset'.