backbone.js initialize listeners vs events
10,604
When you do:
var ViewName = Backbone.View.extend({
initialize: function(){
this.$el.on("eventName", this.functionName, this)
},
functionName: function(){
//whatever
}
});
You have to manually unbind the event when the view is being removed. So, you would have to do something like:
var ViewName = Backbone.View.extend({
initialize: function(){
this.$el.on("eventName", this.functionName, this)
},
functionName: function(){
//whatever
},
remove: function() {
this.$el.off("eventName", this.functionName);
Backbone.View.prototype.remove.apply(this, arguments);
}
});
If you use the events
hash, Backbone takes care of undelegating events when the view is removed. This is all explained in this section of the Backbone.js annotated source.
Related videos on Youtube
Author by
Eric Hannum
Software Engineer at Hack Reactor, San Francisco
Updated on September 14, 2022Comments
-
Eric Hannum over 1 year
I don't understand the difference between putting a "click" listener in an initialize function inside a view and putting it in the events object in the same view. They both listen for DOM events and trigger functions, right? What's the difference?
for example:
var ViewName = Backbone.View.extend({ initialize: function(){ this.$el.on("eventName", this.functionName, this) }, functionName: function(){ //whatever } });
versus:
var ViewName = Backbone.View.extend({ events: { "eventName": "fucntionName" } }, functionName: function(){ //whatever } });
-
Eric Hannum over 10 yearsThanks you :D That's exactly what I was looking for.