简体   繁体   中英

Can I use jQuery .trigger() with event listeners added with addEventListener()?

In my (javascript, jQuery) code, I use two ways of firing events

jQuery('body').trigger('crazy-trigger-event');
jQuery("body").get(0).dispatchEvent(new CustomEvent("crazy-dispatch-event"));

In the snippet here:

http://jsfiddle.net/jts9jhbt/3/

I have registered for custom events using both jQuery .on() and the DOM .addEventListener() methods.

Then I fire the events using both jQuery .trigger() and DOM .dispatchEvent() methods.

It seems like the listeners registered using .on() receive events fired both ways.

But the listeners registered with .addEventListener() only receive events fired using .dispatchEvent().

My use case is that I have a mix of legacy code and jQuery code, and it seems like it's safest to use .dispatchEvent() so that it's compatible with both.

So is there some change to the code I can make so that listeners registered with .addEventListener() can recieve events from .trigger() ?

Simple Answer

No , you can't.

Explanation

The main reason is that jQuery needs to work across multiple browsers and ...

"[...] jQuery's event system is a layer on top of the DOM event system."

Eventhough there are exceptions, there is no efficient way for jQuery to know which events are supported by the browser currently due to the lack of a getEventListeners method. The developers think that the creation of a solution

"[...] isn't possible to do without breaking existing code or causing performance issues ."

If that sounds like a challenge to anybody, you are free to prove them wrong by posting your solution.


The detailed explanation can be found in Dave Methvin 's answers to jQuery's issue #2476 .

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