简体   繁体   中英

How to add an alias for 'addEventListener' method?

It's common in many libraries to use on rather than addEventListener . Personally I find it quite annoying to type addEventListener every time.

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:

Node.prototype.on = Node.prototype.addEventListener

Taking jQuery as an example, on is not an alias. It is a wrapper function around addEventListener (internally, on calls the jQuery.event.add function, which in turn calls 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.

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.

You can add on as an alias for Element.addEventListener as below

Element.prototype.on = Element.prototype.addEventListener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM