Custom Events: Your Own Signals

Custom Events: Your Own Signals in JavaScript: Browsers give us , , and . But what if your app needs a event? Or ? Custom Events allow you to create your own…

Concept Explanation

Browsers give us click, submit, and keydown. But what if your app needs a userLoggedIn event? Or itemAddedToCart?

Custom Events allow you to create your own signals that different parts of your app can listen for. This prevents "Spaghetti Code" because the Shopping Cart doesn't need to know who added the item; it just listens for the "Add" signal.


Syntax or Core Structure

Dispatching (Sending)

const event = new CustomEvent("itemAdded", {
    detail: { productId: 101, name: "Espresso" },
    bubbles: true // Allows the event to travel up the DOM
});

document.dispatchEvent(event);

Listening (Receiving)

document.addEventListener("itemAdded", (e) => {
    console.log(`Updating cart with: ${e.detail.name}`);
});

Real World Example

A Video Player: The "Play Button" sends a playStateChange event. The "Progress Bar", the "Volume Control", and the "Analytics Tracker" all listen for that one event and update themselves independently.


Common Mistakes

  1. Forgetting 'detail': Custom data must be placed inside the detail object. You cannot just add properties to the Event object.
  2. Bubbling: By default, custom events do NOT bubble up to parents. You must set bubbles: true if you want a child element to notify the whole page.
  3. Naming Collisions: Avoid generic names like "update". Use specific names like "myapp:user-update".

Practice Exercises

  1. The Login Signal: Create a button that, when clicked, dispatches a user:login event with a username in the detail.
  2. The Global Listener: Set up a listener on the window object for your custom event and log the data.
  3. The Bubble Test: Create a nested div. Dispatch an event from the inner div and catch it on the outer div (Hint: use bubbles: true).