Is it possible to use jQuery.trigger () with event listeners added by addEventListener ()?

In my (javascript, jQuery) code, I use two ways to fire events

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

In this snippet:

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

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

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

It seems that listeners registered using .on () receive events fired in both directions.

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

My use case is that I have a combination of legacy code and jQuery code, and it seems to be safer to use .dispatchEvent () so that it is compatible with both.

So, are there some changes in the code that I can make so that listeners registered with .addEventListener () can receive events from .trigger ()?

+5
source share
1 answer

Simple answer

No , you can’t.

Explanation

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

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

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

"[...] it is not possible to circumvent a violation of existing code or cause performance problems .

If this sounds like a challenge to someone, you can prove them wrong by posting your decision.


A detailed explanation can be found in Dave Metwin's answer to jQuery Problem # 2476 .

+2
source

Source: https://habr.com/ru/post/1200080/


All Articles