Reputation: 941
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")
;Upvotes: 4
Views: 2194
Reputation: 12452
As far as I know your arrow function is wrong. You can do it this way, because the descructuring of (event: string)
is wrong here. And because () => eventHandler()
is a bit redundant you can just pass in the handler
.
function eventHandler() {
console.log("custom event");
}
["customEvent1", "customEvent2"].forEach(
event => document.addEventListener(event, eventHandler)
);
var event1 = new Event('customEvent1');
document.dispatchEvent(event1);
var event2 = new Event('customEvent2');
document.dispatchEvent(event2);
And keep in mind, you can't trigger events, registered with vanilla js, with jQuery. jQuery only create event-like
callbacks and not real events. So you have to use trigger
then.
// ok
document.addEventListener('customEvent1', eventHandler);
var event1 = new Event('customEvent1');
document.dispatchEvent(event1);
// ok
$(document).on("customEvent2", eventHandler);
$(document).trigger("customEvent2");
// ok
$(document).on("customEvent3", eventHandler);
var event3 = new Event('customEvent3');
document.dispatchEvent(event3);
// not okay
document.addEventListener('customEvent4', eventHandler);
$(document).trigger("customEvent4");
Upvotes: 2
Reputation: 2636
The problem is NOT in the way you attach event handlers. Both addEventListener
and the on
method are fine. However the problem might be either in the forEach
or in the lambdas which changes the scope of this
to something you do not expect. To ensure you refer to the correct object, change the code like this:
var self = this;
["customEvent1", "customEvent2"].forEach(
(event: string) => {
document.addEventListener(event, () => self.eventHandler());
});
$(document).on("customEvent1 customEvent2", () => self.eventHandler());
The this
keyword is a bit tricky as it is contextual
Upvotes: 0
Reputation: 40842
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
Upvotes: 5