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.
$(document).trigger("customEvent1")
;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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With