Reading history

JavaScript Custom Events and EventTarget

6 min read 1 views

Learn to create and dispatch custom events in JavaScript with CustomEvent, detail data, bubbling and classes that extend EventTarget.

Browsers fire events such as click and input when something happens. You can create your own events too, with names that describe what happened in your program: itemadded, checkout or rating-change. One part of the code announces the event, and any number of other parts can listen and react. The announcer never needs to know who is listening, which keeps the pieces of a program loosely connected and easy to change.

In this lesson you will learn

  • Creating events with new CustomEvent(name, { detail })
  • Sending them with dispatchEvent
  • Making your own classes send events by extending EventTarget
  • Letting custom DOM events bubble up to parent elements
  • Listener options such as once

You should know events, event bubbling and delegation and classes.

Your Own Objects Can Send Events

// Any class can send events by extending EventTarget (browsers and Node.js)
class Cart extends EventTarget {
  #items = [];
  add(name, price) {
    this.#items.push({ name, price });
    // detail carries any extra data you want listeners to have
    this.dispatchEvent(new CustomEvent("itemadded", {
      detail: { name, price, count: this.#items.length }
    }));
  }
  checkout() {
    const total = this.#items.reduce((sum, i) => sum + i.price, 0);
    this.dispatchEvent(new CustomEvent("checkout", { detail: { total } }));
    this.#items = [];
  }
}

const cart = new Cart();

// Different parts of the program react without knowing about each other
cart.addEventListener("itemadded", e =>
  console.log(`Badge: ${e.detail.count} item(s)`));
cart.addEventListener("itemadded", e =>
  console.log(`Toast: "${e.detail.name}" added for ${e.detail.price} taka`));
cart.addEventListener("checkout", e =>
  console.log(`Receipt: total ${e.detail.total} taka`), { once: true });

cart.add("Notebook", 60);
cart.add("Pen set", 120);
cart.checkout();
cart.add("Ruler", 25);
cart.checkout();               // the once: true listener has already been removed
console.log("event type check:", new CustomEvent("x") instanceof Event);

Output

Badge: 1 item(s)
Toast: "Notebook" added for 60 taka
Badge: 2 item(s)
Toast: "Pen set" added for 120 taka
Receipt: total 180 taka
Badge: 1 item(s)
Toast: "Ruler" added for 25 taka
event type check: true
  • class Cart extends EventTarget gives the class the same addEventListener, removeEventListener and dispatchEvent methods that DOM elements have. This works in browsers and in Node.js.
  • new CustomEvent("itemadded", { detail: {...} }) creates the event. The detail property carries any data the listeners need.
  • this.dispatchEvent(event) calls every listener for that event name, in the order they were added.
  • The badge and the toast both react to one event, but the cart does not know they exist. A new feature, such as saving the cart, just adds another listener.
  • { once: true } removes the listener after its first run, so the second checkout prints no receipt.

Custom Events in the Page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Custom DOM events</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    .rating button { font-size: 22px; background: none; border: 0; cursor: pointer; color: #bbb; padding: 0 2px; }
    .rating button.on { color: #f9a825; }
    #log { margin: 8px 0 0; padding-left: 18px; color: #333; }
  </style>
</head>
<body>
  <section id="review">
    <p>Rate this lesson:</p>
    <div class="rating" id="stars"></div>
    <ol id="log"></ol>
  </section>
  <script>
    // A small "star rating" widget that announces changes with a custom event
    const stars = document.getElementById("stars");
    for (let i = 1; i <= 5; i++) {
      const b = document.createElement("button");
      b.textContent = "★";
      b.setAttribute("aria-label", i + " stars");
      b.addEventListener("click", () => {
        stars.querySelectorAll("button").forEach((s, n) => s.classList.toggle("on", n < i));
        // bubbles: true lets ancestors hear it, like a click
        stars.dispatchEvent(new CustomEvent("rating-change", {
          bubbles: true,
          detail: { value: i }
        }));
      });
      stars.append(b);
    }

    // The page listens on a parent element: the widget does not know about it
    const log = document.getElementById("log");
    document.getElementById("review").addEventListener("rating-change", e => {
      const li = document.createElement("li");
      li.textContent = "rating-change heard on <section>: value = " + e.detail.value;
      log.append(li);
    });

    stars.children[3].click();   // simulate one click so the demo starts with a result
  </script>
</body>
</html>

Result

  • The star widget dispatches rating-change on its own element whenever a star is clicked. Click a star to see a new line.
  • bubbles: true makes the event travel up through parent elements, like a click does. Without it, only listeners on the widget element itself would hear it.
  • The page listens on the <section>, a parent element. This is event delegation with your own event.
  • The widget could be reused on another page that reacts differently, for example by sending the rating to a server, without changing the widget code.
  • Event names are case-sensitive. Lowercase names with hyphens, such as rating-change, are a common choice and cannot clash with built-in events.
OptionDefaultEffect
detailnullData for listeners, read as e.detail
bubblesfalseTravel up to parent elements
cancelablefalseAllow e.preventDefault(); dispatchEvent then returns false
composedfalseCross shadow DOM boundaries in web components

Common Mistakes

  1. Forgetting bubbles: true, then listening on a parent that never hears the event.
  2. Putting data on the event object directly instead of in detail. Use detail, which is the standard place.
  3. Adding the listener after dispatching. Events are not stored, so a listener added later misses events that already happened.
  4. Using events for everything. If one function simply needs a result from another, a normal function call is clearer.

Practice Exercises

Exercise 1. Make a Timer class that extends EventTarget and dispatches a tick event each second with the seconds passed in detail.

Show answer
class Timer extends EventTarget {
  start() {
    let s = 0;
    this.id = setInterval(() =>
      this.dispatchEvent(new CustomEvent("tick", { detail: ++s })), 1000);
  }
  stop() { clearInterval(this.id); }
}
const t = new Timer();
t.addEventListener("tick", e => console.log(e.detail + "s"));
t.start();

Exercise 2. Dispatch a cancelable beforedelete event, and only delete the item if no listener called preventDefault().

Show answer
const ok = item.dispatchEvent(new CustomEvent("beforedelete", { cancelable: true }));
if (ok) item.remove();   // dispatchEvent returns false if a listener cancelled it

Frequently Asked Questions

Are custom events synchronous?

Yes. dispatchEvent runs every listener immediately and only returns when they have all finished. This is different from events such as click that come from the user, which arrive through the event loop.

What is the difference between Event and CustomEvent?

CustomEvent is an Event with an extra detail property. If you do not need to pass data, new Event("name") works the same way.

Summary

  • new CustomEvent(name, { detail }) creates an event, and dispatchEvent sends it.
  • Extending EventTarget lets any class send events.
  • bubbles: true lets parent elements hear events from inside widgets.
  • Events keep the sender and listeners independent, so features can be added without changing the sender.

Next: JavaScript Keyboard Events and Shortcuts.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *