扩展节点.使用相同名称的addEventListener方法

extending Node.addEventListener method with the same name

本文关键字:addEventListener 方法 节点 扩展      更新时间:2023-09-26

我试图扩展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方法代替?

Thanks in advance

首先让我再次指出(对于其他读者),扩展DOM通常是一个坏主意。

也就是说,如果环境允许,以下是可以做的事情:

您可以保留原始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接口的方法。

再次声明:这不能保证有效,即使它现在有效,将来也可能会失效。

相关文章:
  • 没有找到相关文章