A simple lightweight event bus written in Typescript.
Get started with the documentation
# bun
bun add @kitbag/events
# yarn
yarn add @kitbag/events
# npm
npm install @kitbag/events
import { createEmitter } from '@kitbag/events'
type Events = {
hello: 'world'
}
export const emitter = createEmitter<Events>()
emitter.on('hello', value => {
console.log(value)
})
emitter.emit('hello', 'world')
// console logs "world"
The Events
type defines what events can be emitted and their payload.
type Events = {
ping: 'pong',
userCreated: User,
eventWithNoPayload: void,
}
By default Kitbag Events only emits events within the document. Alternatively, you can configure Events to use a Broadcast Channel which enables you to broadcast events across different windows, tabs, frames or iframes of the same origin.
import { createEmitter } from '@kitbag/events'
const emitter = createEmitter({
broadcastChannel: 'MyChannelName'
})
Define a handler for a single event called "hello"
emitter.on('hello', value => {
console.log(value) // "world"
})
Every event emitted will trigger this callback
emitter.on(event => {
console.log(event) // { kind: 'hello', payload: 'world' }
})
Listen for a single event and then automatically remove the handler
emitter.once(...)
Emitter.on returns the off method for removing an event handler
const off = emitter.on(...)
Manually remove an event handler
const handler = (value) => console.log(value)
const globalHandler = (event) => console.log(event)
emitter.on('hello', handler)
emitter.on(globalHandler)
emitter.off('hello', handler)
emitter.off(globalHandler)
Remove all handlers for a given event
const handler1 = (value) => console.log(value)
const handler2 = (value) => console.log(value)
emitter.on('hello', handler1)
emitter.on('hello', handler2)
emitter.off('hello')
Remove all handlers for all events
emitter.clear()