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
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With