typestar

Custom events in JavaScript

Your own event type, with a payload, bubbling like any other.

function announce(element, stars) {
  const event = new CustomEvent("step:cleared", {
    detail: { stars, at: Date.now() },
    bubbles: true,
    cancelable: true,
  });
  const proceeded = element.dispatchEvent(event);
  return { proceeded, defaultPrevented: event.defaultPrevented };
}

function listen(root) {
  root.addEventListener("step:cleared", (event) => {
    if (event.detail.stars < 1) event.preventDefault();
  });
}

How it works

  1. detail carries the payload.
  2. bubbles decides whether an ancestor can hear it.
  3. preventDefault works if the event is cancelable.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
403
Tokens
101
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 3 of 3 in Events, step 6 of 13 in The browser.

← Previous Next →