I am working on a Backbone application. I created base view which has a destroy method and all other views extend it.
When destroying a view instance I want to make sure that if the view has a model or a collection I am unbinding any events it was listening to.
Assuming I am using underscores’s _.bindAll in the view’s initialize, will the off
statement below remove the references.
var DocumentRow = Backbone.View.extend({
initialize: function() {
_.bindAll( this );
this.model.on('change', this.render);
},
destroy : function() {
// Will this work?
this.model.off(null, null, this);
}
});
or do I need to explicitly bind events like so
this.model.on('change', this.render, this);
this.model.on('change', this.render);will not work the way you want. You need to change it tothis.model.on('change', this.render, this);If you look at the source for the
onmethod (http://backbonejs.org/docs/backbone.html#section-18 ) it does not default yourcontextvariable to anything. So if you don’t set it, the call tooffwill not find the event bindings correctly.FWIW, I get tired of having to do corresponding
onandoffcalls, so I wrote a plugin to handle a lot of it for me: https://github.com/marionettejs/backbone.eventbinderYou can use it like this, and not have to worry about getting the right context or anything else.
The real benefit in this is not having to call
offfor everyon. you only need to make one call tounbindAlland it will unbind all of the events that are stored in the event binder instance.