Skip to main content

Events

Thin wrappers over the DOM 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. These are browser-side helpers; Node's EventEmitter is a different API and is not covered here. The awaiter is onceEvent, not oncefunctions.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 — delay, timeout and settle helpers