扩展Node.addEventListener方法具有相同的名称

问题描述:

我试图延长Node.addEventListener方法,所以我可以做一些活动的管理,如:扩展Node.addEventListener方法具有相同的名称

Node.prototype.on = function (type, listener, useCapture) { 
    'use strict'; 
    var i, evt; 

    this.events = this.events || []; 


    for (i = 0; i < this.events.length; i += 1) { 

     evt = this.events[i]; 

     if (this === evt[0] && type === evt[1]) { 
      this.removeEventListener(type, evt[2], evt[3]); 
      this.events.splice(i, 1); 
     } 

    } 

    this.events.push([this, type, listener, useCapture]); 

    return this.addEventListener(type, listener, useCapture); 
}; 

但在这种情况下,而不是将其命名为on我想把它命名为addEventListener,所以我可以保证任何JavaScript都可以使用它。

所以这里的重点是,如果我将函数命名为addEventListener而不是返回子句,它将导致无限循环。所以我在想如果有什么办法可以调用super方法呢?

在此先感谢

+0

在继续之前,请阅读[扩展DOM有什么问题](http://perfectionkills.com/whats-wrong-with-extending-the-dom)。 –

+0

感谢Felix的提示,其实我知道这篇文章,但是因为这只是在非常封闭和私密的环境下运行,所以我认为它对我的情况不会有问题。但再次感谢您向我展示这一点。 :) – zanona

+0

好吧:)文章还提到,这可能是在封闭的环境中这样做,只是想确保你知道这一点;) –

,首先让我再次指出(其他读者),即extending the DOM is a bad idea in general

这就是说,这里是你可以做,如果环境允许您:

你可以保持参照原addEventListener功能,并与.call调用它。
这仅addEventListener暴露了这种方法的工作原理(即像一个本地JavaScript函数),你实际上可以覆盖addEventListener

// immediate function to create scope 
(function() { 
    // keep a reference to the original method 
    var orig_addEventListener = Element.prototype.addEventListener; 

    Element.prototype.addEventListener = function (type, listener, useCapture) { 
     // your code here 
     //... 
     // call the original method 
     return orig_addEventListener.call(this, type, listener, useCapture); 
    }; 

}()); 

注意addEventListenerElement接口,而不是Node接口的方法。

再次说明:这并不保证能够正常工作,即使它现在有效,它也可能在未来破裂。

+0

非常感谢你的帮助菲利克斯,它工作得很漂亮确实... – zanona