Events

EventTarget is the base class for objects that emit events. Extend it, register listeners with addEventListener(), and send an event with dispatchEvent(). Event carries the event type and flags; CustomEvent adds a detail value for your own data.

  • new EventTarget() creates an event target.
  • target.addEventListener(type, listener, options) registers a listener. options accepts capture, once, passive, and signal.
  • target.removeEventListener(type, listener, options) removes a listener.
  • target.dispatchEvent(event) dispatches an event and returns false when a cancelable event was canceled.
  • new Event(type, options) creates an event. Options are bubbles, cancelable, and composed.
  • new CustomEvent(type, options) creates an event with a detail value, which defaults to null.
  • event.type, event.target, event.currentTarget, event.defaultPrevented, and the other Event properties describe the dispatch.

Creating an Event or CustomEvent without a type throws a TypeError, as does passing a value that is not an Event to dispatchEvent().

Usage#

A scheduled job checking two HTTP endpoints:

class PageChecker extends EventTarget {
  constructor(urls) {
    super();
    this.urls = urls;
  }

  async run() {
    for (const url of this.urls) {
      const response = await fetch(url);
      const body = await response.text();

      this.dispatchEvent(
        new CustomEvent("checked", {
          detail: { url, status: response.status, chars: body.length },
        }),
      );
    }
  }
}

const checker = new PageChecker([
  "https://httpbin.org/json",
  "https://httpbin.org/uuid",
]);

checker.addEventListener("checked", (event) => {
  const { url, status, chars } = event.detail;
  console.log(`${status} ${chars} chars ${url}`);
});

await checker.run();

Output shape:

200 429 chars https://httpbin.org/json
200 53 chars https://httpbin.org/uuid

httpbin.org is a public request-and-response sandbox, so the example makes real HTTP calls without an account or an API key.

A cancelable validation hook before saving a record:

const hooks = new EventTarget();
const record = { email: "" };

hooks.addEventListener("beforeSave", (event) => {
  if (!record.email) {
    event.preventDefault();
  }
});

const event = new Event("beforeSave", { cancelable: true });
console.log(hooks.dispatchEvent(event)); // false

Stopping a listener when a run hits its time limit:

const job = new EventTarget();
const controller = new AbortController();

job.addEventListener("progress", () => console.log("progress"), {
  signal: controller.signal,
});

job.dispatchEvent(new Event("progress")); // progress
controller.abort();
job.dispatchEvent(new Event("progress")); // no output

Differences from the standard#

  • Events do not propagate through a node tree. There are no capture or bubble phases; listeners run in registration order at the target. composedPath() returns the current target during dispatch and an empty array afterwards.
  • The deprecated initEvent() and initCustomEvent() methods are not available.
  • Event handler attributes such as onclick are not part of EventTarget. Interfaces that define them, such as AbortSignal, add their own.

Documentation#