Eventtarget

The WHATWG EventTarget bus: addEventListener / removeEventListener / dispatchEvent, distinct from Node's EventEmitter. Single- target dispatch (no DOM capture/bubble tree). See

const bus = new EventTarget()

// Register a listener and fire the event twice.
let pings = 0
bus.addEventListener("ping", (e: Event) => {
	pings = pings + 1
	console.log("ping " + pings)      // ping 1 / ping 2
})
bus.dispatchEvent(new Event("ping"))
bus.dispatchEvent(new Event("ping"))

// A CustomEvent's detail reaches the listener.
bus.addEventListener("message", (e: CustomEvent) => {
	console.log("got: " + e.detail)   // got: hello
})
bus.dispatchEvent(new CustomEvent("message", { detail: "hello" }))

// removeEventListener stops future dispatches (the listener must be a named
// value so it matches by identity).
const onTick = (e: Event) => console.log("tick")
bus.addEventListener("tick", onTick)
bus.dispatchEvent(new Event("tick"))    // tick
bus.removeEventListener("tick", onTick)
bus.dispatchEvent(new Event("tick"))    // (nothing)

// { once: true } auto-removes after the first dispatch.
bus.addEventListener("boot", (e: Event) => console.log("boot once"), { once: true })
bus.dispatchEvent(new Event("boot"))    // boot once
bus.dispatchEvent(new Event("boot"))    // (nothing)

// dispatchEvent returns false when a listener calls preventDefault() on a
// cancelable event (a non-cancelable event's preventDefault is a no-op).
bus.addEventListener("save", (e: Event) => e.preventDefault())
const proceeded = bus.dispatchEvent(new Event("save", { cancelable: true }))
console.log("proceeded: " + proceeded)  // proceeded: false

// A listener may omit the event parameter — WHATWG always calls it with the
// event, and a zero-arg handler just ignores it.
bus.addEventListener("wake", () => console.log("woke up"))
bus.dispatchEvent(new Event("wake"))    // woke up

// removeEventListener also matches a listener passed by a named-function
// reference (not only a const-bound arrow) — every reference to a named
// function has the same identity.
function onBeat(e: Event): void { console.log("beat") }
bus.addEventListener("heartbeat", onBeat)
bus.dispatchEvent(new Event("heartbeat"))    // beat
bus.removeEventListener("heartbeat", onBeat)
bus.dispatchEvent(new Event("heartbeat"))    // (nothing)
View source on GitHubexamples/events/eventtarget.ts