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");- Expected result: The console prints Saved 7, then Dispatched; the second saved event has no remaining listener.
- once removes the listener after its first invocation.
- 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