替换addEventListener

Dio*_*des 4

我有很多代码用于addEventListener缩小库,文件......,但我需要在IE8中使用此代码,所以替换addEventListeneraddEvent:

 /*
  * 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);
             });
     }
 }
Run Code Online (Sandbox Code Playgroud)

我可以"覆盖" window.addEventListener,但是如何在其他对象中覆盖此方法?

在此先感谢您的问候

I a*_*ica 5

要访问它,你会在现代浏览器,你会想方法添加到以同样的方式Window,HTMLDocumentElement原型.

(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;
    }
})();
Run Code Online (Sandbox Code Playgroud)

注意:虽然我们规范了对函数的访问并解决了this问题,但我们还没有将事件规范化为w3c标准.像这样,将缺少的属性,等等 看看Mozilla的垫片.event.targetevent.relatedTarget

addEventListener()