Skip to content

Events ​

Introduction ​

Events let one part of your application announce that something happened without knowing who cares. When a user registers, you might send a welcome email, record an audit entry and update a counter. Instead of calling all three from the registration code, you dispatch a user.created event and let each concern listen for it on its own. The Dispatcher in @plinthjs/events does the wiring.

bash
pnpm add @plinthjs/events

Events are identified by a string name, and may carry a payload of any type. The dispatcher has no clock, no randomness and no I/O of its own, so its behaviour is fully predictable in tests.

Listening and dispatching ​

Create a dispatcher, register listeners with listen, and fire events with dispatch.

ts
import { Dispatcher } from '@plinthjs/events'

const events = new Dispatcher()

events.listen('user.created', (user, name) => {
  console.log(`${name} fired for`, user)
  return 'welcome-sent'
})

const results = await events.dispatch('user.created', { id: 1 })
// logs: user.created fired for { id: 1 }
// results => ['welcome-sent']

A listener receives the payload first and the event name second. dispatch always returns a promise: it awaits asynchronous listeners and resolves to an array of their return values, in the order the listeners ran.

ts
events.listen('report.ready', async (report) => {
  await notifyOwner(report)
  return 'notified'
})

You can register one listener for several events by passing an array:

ts
events.listen(['user.created', 'user.updated'], (user) => {
  // runs for either event
})

Listeners for one event run in the order you registered them. Dispatching an event nobody listens to is fine: it resolves to an empty array.

Event classes ​

You can also dispatch an event object, an instance of a class, as the only argument. The class name is the event name and the instance is the payload. listen, once, forget and hasListeners accept the class itself in place of a string, so you never type the name by hand.

ts
class OrderShipped {
  constructor(readonly id: number) {}
}

events.listen(OrderShipped, (event) => {
  console.log('shipped', (event as OrderShipped).id)
})

await events.dispatch(new OrderShipped(7)) // listeners registered for OrderShipped, 'OrderShipped' or a matching wildcard
await events.dispatch('OrderShipped', { id: 8 }) // string dispatch is unchanged and reaches the same listeners

Wildcard listeners such as Order* receive (eventName, payload) as usual, so for a class event the payload is the instance. until accepts an event object too.

Because of this, a Dispatcher can be passed straight to anything that takes a { dispatch(event: object) } seam: the cache, auth guards, the logger, the mailer, queue drivers and the notification sender. Listen for the event classes those packages export (CacheHit, Login, MessageLogged, MessageSent, JobFailed, NotificationSent, and so on). Those seams call dispatch and ignore the returned promise, so keep listeners from throwing, or handle errors inside them.

ts
import { CacheHit, CacheManager } from '@plinthjs/cache'

const events = new Dispatcher()
events.listen(CacheHit, (event) => console.log('hit', (event as CacheHit).key))

const caches = new CacheManager({ events })

Wildcard listeners ​

A * anywhere in a name turns it into a pattern. A star matches any run of characters, including dots.

ts
events.listen('user.*', (name, payload) => {
  console.log('audit', name, payload)
})

await events.dispatch('user.created', { id: 1 })
// logs: audit user.created { id: 1 }

Notice that wildcard listeners receive the event name first and the payload second, the reverse of an ordinary listener. That is because the name is the interesting part when one listener handles many events.

Wildcards can sit at the start, the end or in the middle (*.created, user.*, *). For one dispatch, concrete listeners run first, then matching wildcard listeners.

ts
events.listen('user.created', () => 'one')
events.listen('user.*', () => 'audit')

await events.dispatch('user.created') // => ['one', 'audit']

Listening once ​

once registers a listener that is removed after it first runs. It works with wildcard patterns too.

ts
events.once('app.booted', () => 'first boot only')

await events.dispatch('app.booted') // => ['first boot only']
await events.dispatch('app.booted') // => []

Stopping propagation ​

If a listener returns exactly false, no later listener runs and dispatch resolves with the results collected so far (the false itself is not included).

ts
events.listen('order.placing', () => 'checked stock')
events.listen('order.placing', () => false) // veto
events.listen('order.placing', () => 'never runs')

await events.dispatch('order.placing') // => ['checked stock']

Only false halts propagation. Returning undefined or null does not.

Getting the first answer ​

until dispatches an event but stops at the first listener that returns something other than null or undefined, and resolves to that value. It resolves to undefined if no listener answers. Use it when listeners are asked a question rather than told a fact.

ts
events.listen('price.lookup', () => null) // no opinion
events.listen('price.lookup', () => 1999) // answers
events.listen('price.lookup', () => 2999) // never asked

await events.dispatch('price.lookup') // runs every listener
await events.until('price.lookup', { sku: 'A1' }) // => 1999

Inspecting and removing listeners ​

ts
events.hasListeners('user.created') // => true
events.listenerCount('user.created') // => 2 (includes matching wildcards)

events.forget('user.created') // remove the listeners registered for that exact name
events.forget('user.*') // remove the wildcard listeners registered with that exact pattern

forget takes the exact name or pattern you registered with. forget('user.created') does not remove a user.* listener, and forget('user.*') does not remove listeners registered for user.created.

Event subscribers ​

A subscriber groups related listeners in one object. Give it a subscribe(dispatcher) method, then hand it to the dispatcher.

ts
import { Dispatcher } from '@plinthjs/events'
import type { Subscriber } from '@plinthjs/events'

class UserSubscriber implements Subscriber {
  subscribe(events: Dispatcher): void {
    events.listen('user.created', (user) => sendWelcome(user))
    events.listen('user.deleted', (user) => purge(user))
  }
}

const events = new Dispatcher().subscribe(new UserSubscriber())

This keeps all the wiring for one concern in one place and out of your application bootstrap code.

Deferring events ​

Sometimes you want to collect events now and fire them together later, for example after a database transaction commits. push records an event without calling any listener, and flush dispatches everything pushed under that name, in push order.

ts
events.listen('invoice.created', (invoice) => console.log('flushed', invoice))

events.push('invoice.created', 1).push('invoice.created', 2)
// nothing has run yet

await events.flush('invoice.created')
// logs: flushed 1
// logs: flushed 2

flush resolves to the listener results from all the flushed dispatches, and it empties the deferred list, so flushing again does nothing. To throw deferred events away unfired, call forgetPushed(event), or forgetPushed() for all of them.

Queued listeners ​

Some listeners do slow work, such as sending an email, and should not delay the code that dispatched the event. Wrap such a listener with queued(). At dispatch time the dispatcher does not run it; it hands a job to a queue seam instead.

ts
import { Dispatcher, queued } from '@plinthjs/events'
import type { QueuedListenerJob } from '@plinthjs/events'

const jobs: QueuedListenerJob[] = []

const events = new Dispatcher({
  push(job) {
    jobs.push(job) // a real app would hand this to a queue
  },
})

events.listen(
  'mail.requested',
  queued((payload) => sendMail(payload)),
)
events.listen('mail.requested', () => console.log('inline listener'))

await events.dispatch('mail.requested', { to: 'ada@example.com' })
// logs: inline listener
// jobs.length => 1, the queued listener has not run yet

jobs[0].event // => 'mail.requested'
jobs[0].payload // => { to: 'ada@example.com' }
await jobs[0].handle() // runs the deferred listener now

The seam is any object with a push(job) method. A job carries the event name, the payload and a handle() method that runs the listener with its original arguments. Pass the seam to the constructor, or set it later with events.setQueue(seam).

The default seam runs each job immediately, so a dispatcher with no queue configured treats queued() listeners as ordinary listeners. You can also import it as runInlineQueue.

WARNING

A queued listener is fire and forget. It contributes only undefined to the results array, and it cannot return false to stop propagation, because by the time it runs the dispatch has already moved on.

For running jobs in the background, see Queues.

Testing ​

Call fake() on a dispatcher to get a FakeDispatcher. Pass the fake to the code under test in place of the real dispatcher. It records every dispatched event instead of running any listener, and it offers assertion helpers.

ts
import { Dispatcher } from '@plinthjs/events'

const events = new Dispatcher().fake()

await events.dispatch('order.shipped', { id: 5 })
await events.dispatch('order.shipped', { id: 6 })

events.assertDispatched('order.shipped')
events.assertDispatched('order.shipped', (payload) => (payload as { id: number }).id === 5)
events.assertDispatchedTimes('order.shipped', 2)
events.assertNotDispatched('order.cancelled')

events.dispatched('order.shipped') // => [{ id: 5 }, { id: 6 }]
events.hasDispatched('order.shipped') // => true

The assertions throw with a descriptive message when they fail, for example The expected [order.cancelled] event was not dispatched. assertNothingDispatched() checks that no event fired at all. All the assertion helpers return the fake, so they chain.

On a fake, listen, once and subscribe are accepted but do nothing, and dispatch always resolves to an empty array. until records the event and resolves to undefined. push and flush work as on a real dispatcher but record the events (on flush) instead of running listeners.

TIP

Because a fake never runs listeners, test your listeners separately by registering them on a real dispatcher (or calling them directly), and use the fake only to check that the right events are fired from your code.

Released under the MIT License.