Question 65

Question

Explain the difference between EventTarget.dispatchEvent() and EventTarget.addEventListener().

Answer

1. EventTarget.addEventListener():

  • Purpose: Registers a function (a "listener") that will be called when a specific type of event occurs on an EventTarget object (e.g., a button, a div, the entire document).

  • How it works: You provide:

    • The type of event you want to listen for (e.g., 'click', 'mouseover', 'submit').

    • A callback function that will execute when the event happens. This function typically receives the event object as an argument, giving you information about what happened and how to respond.

    • Optional options: You can specify things like whether to listen for the event only once (once: true), or in a particular "capture" phase of event bubbling (capturePhase).

2. EventTarget.dispatchEvent():

  • Purpose: Triggers (or "dispatches") an event on an EventTarget object. This means you are manually initiating an event.

  • How it works: You create an Event object and pass it to the dispatchEvent() method. The event will bubble up through the DOM tree (if bubbles: true is set), triggering any listeners that have been registered for that type of event.

Analogy:

Think of addEventListener() as setting up a trap, waiting for a specific kind of event to happen. When dispatchEvent() is called, it's like throwing a ball (the event) into the air. The ball will bounce around and activate any traps (listeners) it hits along the way.

Last updated