Passing Objects Usage Scenarios
This can also be helpful if we want to pass arguments to the event handlers.
Sometimes we may want to create event handlers dynamically which are similar to each other. In this case passing different objects to addEventListener can be used to register similar kind of event handler dynamically.
How To?
Let’s see how can we pass objects to addEventListener:
Instead of passing a callback we can directly pass a object with an handleEvent property assigned to an function. Now handleEvent property becomes the event handler.
Supported Browsers
Some older IE browsers don’t support it and also some mobile browsers don’t. This is a polyfill I have written which overrides the functionality of the addEventListener method to support this functionality.
Function.prototype.bind=Function.prototype.bind||function(b){if(typeof this!=="function"){throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");}var a=Array.prototype.slice,f=a.call(arguments,1),e=this,c=function(){},d=function(){return e.apply(this instanceof c?this:b||window,f.concat(a.call(arguments)));};c.prototype=this.prototype;d.prototype=new c();return d;};
//now polyfill addEventListener
//override EventTarget.addEventListener
EventTarget.prototype.old_addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(eventType, obj, bubble){
if(typeof obj == "function"){
this.old_addEventListener(eventType, obj, bubble);
}
else if(typeof obj == "object" && obj.handleEvent){
this.old_addEventListener(eventType, obj.handleEvent.bind(obj), bubble);
}
else{
throw e;
}
}
Leave a Reply