Codectionary / Developer documentation / JavaScript

Application Events with EventTarget and CustomEvent

EventTarget provides a small event dispatch mechanism independent of DOM elements. CustomEvent carries application data through detail. dispatchEvent invokes listeners synchronously; a custom event does not automatically become an asynchronous message or provide isolation between listeners.

Syntax

target.dispatchEvent(new CustomEvent("saved", { detail: { id: 7 } }));

Examples

Application Events with EventTarget and CustomEvent: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: The console prints Saved 7, then Dispatched; the second saved event has no remaining listener.

const bus = new EventTarget();
bus.addEventListener("saved", event => {
  console.log(`Saved ${event.detail.id}`);
}, { once: true });
bus.dispatchEvent(new CustomEvent("saved", { detail: { id: 7 } }));
bus.dispatchEvent(new CustomEvent("saved", { detail: { id: 8 } }));
console.log("Dispatched");
  1. Expected result: The console prints Saved 7, then Dispatched; the second saved event has no remaining listener.
  2. once removes the listener after its first invocation.
  3. detail is the same referenced value supplied by the sender, not a structured clone.

Best practices

  • Document event names and payload contracts.
  • Use explicit cleanup or AbortSignal for long-lived listeners.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading