使用相同的名称扩展 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
而不是在 return 子句上,则会导致无限循环。所以我在想是否有什么办法让它调用 super
方法呢?
提前致谢
I'm trying to extend the Node.addEventListener
method so I can do some events management like:
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);
};
But in this case, instead of naming it on
I would like to name it the same addEventListener
so I can guarantee any javascript will work on it.
So the point here is that if I name the function as addEventListener
instead on on the return clause it will cause an endless loop. so I was thinking if is there any way to make it call the super
method instead?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先让我再次指出(对于其他读者), 扩展 DOM 是总的来说这是一个坏主意。
也就是说,如果环境允许,您可以执行以下操作:
您可以保留对原始
addEventListener
函数的引用,并使用.call< 调用它/代码>。
仅当
addEventListener
公开此方法(即类似于本机 JavaScript 函数)并且您实际上可以覆盖addEventListener
时,此方法才有效:请注意,
addEventListener
是一个Element
接口的方法,而不是Node
接口。再次强调:这不能保证有效,即使现在有效,将来也可能会崩溃。
First of all let me point out again (for other readers), that extending the DOM is a bad idea in general.
That said, here is what you could do, if the environment lets you:
You can keep a reference to the original
addEventListener
function and call it with.call
.This only works if
addEventListener
exposes this method (i.e. is like a native JavaScript function) and you can actually overwriteaddEventListener
:Notice that
addEventListener
is a method of theElement
interface, not theNode
interface.Again: This is not guaranteed to work, and even if it works now, it might break in the future.