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
- Forgetting 'detail': Custom data must be placed inside the
detailobject. You cannot just add properties to the Event object. - Bubbling: By default, custom events do NOT bubble up to parents. You must set
bubbles: trueif you want a child element to notify the whole page. - Naming Collisions: Avoid generic names like "update". Use specific names like "myapp:user-update".
Practice Exercises
- The Login Signal: Create a button that, when clicked, dispatches a
user:loginevent with a username in thedetail. - The Global Listener: Set up a listener on the
windowobject for your custom event and log the data. - 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).