Skip to main content

Events

Runtime: any — Node.js ≥ 22 or a modern browser (EventTarget and CustomEvent are globals in both)

Thin wrappers over the EventTarget API — add a listener, dispatch a CustomEvent, await a single event as a promise. on returns its own removal function, so cleanup is a value you can store and call rather than a removeEventListener you must remember to mirror argument for argument. They work on any EventTarget — a DOM element in the browser, or a plain new EventTarget() in Node; Node's EventEmitter is a different API and is not covered here. The awaiter is onceEvent, not once — functions.once memoises a call, and the two were separated so neither name has to be read twice.

Example​

import { emit, on, onceEvent } from '@rtorcato/js-common/events'

// `on` returns its own teardown, so cleanup is a value rather than a listener
// signature you have to mirror argument for argument.
const off = on(window, 'resize', () => relayout())
onUnmount(off)

await onceEvent(panel, 'transitionend') // await a single event
emit(window, 'app:ready', { at: Date.now() }) // dispatch a CustomEvent

Import​

import { emit, on, onceEvent } from '@rtorcato/js-common/events'

Exports​

NameSummary
emitDispatches a custom event on the target.
onAdds an event listener and returns a function to remove it.
onceEventWaits for a single event to occur and resolves a promise.
preventDefaultPrevents the default action for an event.
stopPropagationStops propagation for an event.

See also​

  • abortController — cancel in-flight work with an AbortSignal
  • functions — debounce, throttle, once (memoise a call), compose
  • promises — timeout and error-tuple helpers