@kitbag/events
v0.1.1
Published
A simple lightweight event bus written in Typescript.
Downloads
282
Readme
@kitbag/events
A simple lightweight event bus written in Typescript.
Getting Started
Get started with the documentation
Installation
# bun
bun add @kitbag/events
# yarn
yarn add @kitbag/events
# npm
npm install @kitbag/events
Create an Emitter
import { createEmitter } from '@kitbag/events'
type Events = {
hello: 'world'
}
export const emitter = createEmitter<Events>()
Add Listeners
emitter.on('hello', value => {
console.log(value)
})
Emit Events
emitter.emit('hello', 'world')
// console logs "world"
Events
The Events
type defines what events can be emitted and their payload.
type Events = {
ping: 'pong',
userCreated: User,
eventWithNoPayload: void,
}
Usage
Broadcast Channel
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'
})
Single Event Handler
Define a handler for a single event called "hello"
emitter.on('hello', value => {
console.log(value) // "world"
})
Global Event Handler
Every event emitted will trigger this callback
emitter.on(event => {
console.log(event) // { kind: 'hello', payload: 'world' }
})
Single Use Handler
Listen for a single event and then automatically remove the handler
emitter.once(...)
Removing listeners
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()