When it comes to event-based JS, there are two main APIs to consider: event listeners and event handlers. Event listeners can be registered using addEventListener
, while event handlers are typically registered with an API similar to
target.onfoobar = (ev) => { ... }
. Events can then be triggered using dispatchEvent
. However, the exact timing and behavior of how dispatchEvent
interacts with event handlers remains a bit unclear to me.
In my initial understanding, I believed that event handlers were invoked at the conclusion of dispatchEvent
. This led me to imagine dispatchEvent
functioning in a manner similar to this:
EventTarget.prototype.dispatchEvent = function(event) {
// Initial dispatch to this.listeners, followed by:
const handler = this['on'+event.type];
if (handler) handler(event);
};
There are instances where dispatchEvent
indeed triggers the event handler:
window.onclick = () => console.log("this IS called!!");
window.dispatchEvent(new Event("click"));
However, there are also scenarios in which dispatchEvent
does NOT invoke the event handler:
window.onxyz = () => console.log("this is NOT called!!");
window.dispatchEvent(new Event("xyz"));
The inconsistency in these outcomes leaves me puzzled. What factors differentiate between these two situations? Is it possible that "click" is classified as a "standard" event type whereas "xyz" is not? If so, what exactly defines a "standard" event type, and how does dispatchEvent
discern between them?