I'm sure for most of you it's the old news, but here's a short reminder anyway:
song = {
handleEvent: function (event) {
switch (event.type) {
case: "click":
console.log(this.name);
break;
},
name: "Yesterday"
};
songNode.addEventListener("click", song, false);
We can use an object obj
that has handleEvent
property as a handler on any DOM object to catch its events
and have event handler's context set to that object obj
without the use of Function.prototype.bind
.
This comes in handy when working with Backbone:
var SongView = Backbone.View.extend({
handleEvent: function (e) {
switch (e.type) {
case "loadeddata":
this.trigger('loaded');
break;
case "ended":
this.trigger('ended');
break;
case "error":
this.trigger('error');
break;
}
},
initialize: function () {
var events = ['loadeddata', 'ended', 'error'];
_.forEach(events, function (eventType) {
this.el.removeEventListener(eventType, this, false);
this.el.addEventListener(eventType, this, false);
}, this);
}
});
Following the example above eliminates the need to bind all DOM events handlers (saving on many closures), places the event handling logic in one place and allows for easy removal of previously set handlers, without repetitively storing refences to these handlers.