Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ?

like image 526
user3931014 Avatar asked Aug 12 '14 04:08

user3931014


1 Answers

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.

like image 144
dargmuesli Avatar answered Oct 14 '22 16:10

dargmuesli