@plugola/message-bus
TypeScript icon, indicating that this package has built-in type declarations

5.0.0 • Public • Published

@plugola/message-bus

Plugola event management

Examples

Simple Event Handling

const messageBus = new MessageBus<
  {
    foo: [string]
    bar: [number, number]
  },
  {},
  {}
>()

messageBus.start()

const broker = messageBus.broker('broker name')

broker.on('foo', (str) => {
  console.info(str)
})

broker.on('bar', (num1, num2) => {
  console.info(num1 + num2)
})

broker.emit('foo', 'hello world')
broker.emit('bar', 1, 2)

Queued Events

Events are queued until, you call messageBus.start().

const messageBus = new MessageBus<{ foo: [string] }, {}, {}>()
const broker = messageBus.broker('my broker')

broker.on('foo', () =>
  console.info("I'll log once messageBus.start() is called")
)
broker.emit('foo')

messageBus.start()

Subcription Specificity

You can narrow down you subsciption by the arguments emitted.

const messageBus = new MessageBus<{ foo: [string, string] }, {}, {}>()
const broker = messageBus.broker('my broker')

messageBus.start()

broker.on('foo', 'bar', 'bazzle', () => {
  console.info('I only care when foo is emitted with "bar" and "bazzle"')
})

broker.emit('foo', 'rab', 'elzzab') // no subscriptions registered for this event
broker.emit('foo', 'bar', 'bazzle')

Event Interception

You can intercept messages to modify their arguments.

const messageBus = new MessageBus<{ foo: [string] }, {}, {}>()
const broker = messageBus.broker('my broker')

messageBus.start()

broker.intercept('foo', (str) => [str.reverse()])

broker.on('foo', console.info) // rab

broker.emit('foo', 'bar')

You can also cancel the event completely.

import { CancelEvent } from '@plugpola/message-bus'

broker.intercept('foo', () => CancelEvent)

broker.emit('foo') // no subscriptions will get called

Event Generators

You can register any number of "generators" to an event.

const messageBus = new MessageBus<
  {},
  { foo: { args: [string]; yield: [string] } },
  {}
>()

const broker = messageBus.broker('my broker')

messageBus.start()

broker.generator('foo', async function* (thing) {
  yield `${thing} is a thing`
})

broker.generator('foo', 'bar', async function* (thing) {
  yield 'Bars are great'
})

for await (const item of broker.iterate('foo', 'bar')) {
  // item = "bar is a thing" | "Bars are great"
}

Readme

Keywords

none

Package Sidebar

Install

npm i @plugola/message-bus

Weekly Downloads

6

Version

5.0.0

License

MIT

Unpacked Size

109 kB

Total Files

71

Last publish

Collaborators

  • johngeorgewright