Replace addEventListener
I have a lot of code that uses addEventListener
in mini libraries, files ... but I need to do this code in IE8 , so instead ofaddEventListener
addEvent
/*
* Register the specified handler function to handle events of the specified
* type on the specified target. Ensure that the handler will always be
* invoked as a method of the target.
*/
function addEvent(type, handler) {
if (this.addEventListener)
this.addEventListener(type, handler, false);
else {
this.attachEvent("on" + type,
function(event) {
return handler.call(this, event);
});
}
}
I can "override" window.addEventListener
, but how can I override this method in other objects?
Thanks in advance Relationship
source to share
To access it in the same way as in modern browsers, you will want to add a method to prototypes Window
, HTMLDocument
and Element
.
(function(){
if (!("addEventListener" in window)) {
function addEventListener(type, handler) {
var _this = this;
this.attachEvent("on" + type, function(){
handler.call(_this, window.event);
});
}
Window.prototype.addEventListener = addEventListener;
HTMLDocument.prototype.addEventListener = addEventListener;
Element.prototype.addEventListener = addEventListener;
}
})();
Note. While we normalized function access and addressed the problem this
, we did not normalize this event to w3c standards. Thus, properties such as , etc. will be missing .
Check out the Mozilla shim.event.target
event.relatedTarget
addEventListener()
source to share