[英]How to add an alias for 'addEventListener' method?
It's common in many libraries to use on
rather than addEventListener
.在许多库中使用
on
而不是addEventListener
很常见。 Personally I find it quite annoying to type addEventListener
every time.我个人觉得每次都输入
addEventListener
很烦人。
Is there a way to add an alias?有没有办法添加别名?
Thanks.谢谢。
If you want to create just an alias, you can add a new reference of the addEventListener
method to a brand new on
method like this:如果只想创建别名,可以将
addEventListener
方法的新引用添加到全新的on
方法,如下所示:
Node.prototype.on = Node.prototype.addEventListener
Taking jQuery as an example, on
is not an alias.以 jQuery 为例,
on
不是别名。 It is a wrapper function around addEventListener
(internally, on
calls the jQuery.event.add
function, which in turn calls addEventListener
).它是
addEventListener
的包装函数( on
内部,调用jQuery.event.add
函数,后者又调用addEventListener
)。 The approach will be similar in other libraries.该方法在其他库中将是类似的。
As Nhor pointed out, you can create a new function pointing to addEventListener
, but the semantics will be different than in most libraries.正如 Nhor 指出的那样,您可以创建一个指向
addEventListener
的新函数,但语义将与大多数库中的不同。
Thanks to other answers, I end up with this:感谢其他答案,我最终得到了这个:
EventTarget.prototype.on = EventTarget.prototype.addEventListener
I found in documentation that addEventListener
method belongs to EventTarget
, so that's the right object to add an alias.我在文档中发现
addEventListener
方法属于EventTarget
,因此这是添加别名的正确对象。
You can add on
as an alias for Element.addEventListener
as below您可以添加作为
Element.addEventListener
on
别名,如下所示
Element.prototype.on = Element.prototype.addEventListener
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.