Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.addEventListener vs. $(document).on

I somehow found a bit strange behavior of adding eventlisteners to document. While adding listeners to HTMLElements works fine adding a listener to document doesn't work. But the strange thing is, that using jQuery makes it work.

So can someone explain, why this two functions are not doing the exact same thing?

["customEvent1", "customEvent2"].forEach(
    (event: string) => {
        document.addEventListener(event, () => this.eventHandler());
    });

$(document).on("customEvent1 customEvent2", () => this.eventHandler());

EDIT: Well it seams that there is some misunderstanding about the environment.

  1. The function is surrounded by a class
  2. I'm using TypeScript/ES6
  3. the EventHandler is a class method
  4. the custom event is triggered with $(document).trigger("customEvent1");
like image 505
DaSch Avatar asked Mar 11 '23 07:03

DaSch


1 Answers

jQuery does not create a native event if you use $(document).trigger("customEvent2"); (jquery src/event/trigger.js), it only emulates the native event handling.

So if you register an event handler using document.addEventListener then your cannot use $(document).trigger( for those events.

But if you create and dispatch an event using native code:

var event = new Event('customEvent1');
document.dispatchEvent(event);

Then you can catch it with both document.addEventListener and jQuery's .on

like image 156
t.niese Avatar answered Mar 16 '23 02:03

t.niese