Document.addeventlistener Vs. $(document).on
Solution 1:
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:
varevent = new Event('customEvent1');
document.dispatchEvent(event);
Then you can catch it with both document.addEventListener
and jQuery's .on
Solution 2:
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
.
functioneventHandler() {
console.log("custom event");
}
["customEvent1", "customEvent2"].forEach(
event =>document.addEventListener(event, eventHandler)
);
var event1 = newEvent('customEvent1');
document.dispatchEvent(event1);
var event2 = newEvent('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.
// okdocument.addEventListener('customEvent1', eventHandler);
var event1 = newEvent('customEvent1');
document.dispatchEvent(event1);
// ok
$(document).on("customEvent2", eventHandler);
$(document).trigger("customEvent2");
// ok
$(document).on("customEvent3", eventHandler);
var event3 = newEvent('customEvent3');
document.dispatchEvent(event3);
// not okaydocument.addEventListener('customEvent4', eventHandler);
$(document).trigger("customEvent4");
Solution 3:
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
Post a Comment for "Document.addeventlistener Vs. $(document).on"