@guanghechen/eventbus
v7.1.1
Published
A simple event bus with disposable support.
Readme
A simple event bus with disposable support.
Features
- Type-specific listeners (
on/once) and global subscribers (subscribe) - Returns
IUnsubscribablefor easy cleanup - Implements
IBatchDisposablefor resource management - Exception isolation: one handler's error won't stop other handlers
- Alias methods:
offforremoveListener,emitfordispatch listenerCount()to get the number of listeners
Install
npm
npm install --save @guanghechen/eventbusyarn
yarn add @guanghechen/eventbus
Usage
import type { IEvent, IEventHandler } from '@guanghechen/eventbus'
import { EventBus } from '@guanghechen/eventbus'
enum EventTypes {
INIT = 'INIT',
EXIT = 'EXIT',
}
const eventBus = new EventBus<EventTypes>('my-bus')
const handle: IEventHandler<EventTypes> = (evt, eventBus): void => {
console.log('evt:', evt)
}
// Listen for specific event, returns IUnsubscribable
const unsub1 = eventBus.on(EventTypes.INIT, handle)
// Listen for specific event, auto-removed after first call
const unsub2 = eventBus.once(EventTypes.INIT, handle)
// Subscribe to all events
const unsub3 = eventBus.subscribe(handle)
// Dispatch an event
eventBus.dispatch({ type: EventTypes.INIT, payload: { id: 1 } })
// Or use alias
eventBus.emit({ type: EventTypes.INIT, payload: { id: 1 } })
// Remove listener
eventBus.off(EventTypes.INIT, handle)
// Or use unsubscribable
unsub1.unsubscribe()
// Get listener count
console.log(eventBus.listenerCount()) // all listeners + subscribers
console.log(eventBus.listenerCount(EventTypes.INIT)) // only INIT listeners
// Cleanup all listeners and subscribers
eventBus.cleanup()
// Dispose the event bus (also disposes registered disposables)
eventBus.dispose()API
EventBus<T>
| Method | Description |
| ----------------------------------- | ----------------------------------------------------- |
| on(type, handle) | Listen for a specific event type |
| once(type, handle) | Listen for a specific event type, auto-removed |
| off(type, handle) | Remove a listener (alias of removeListener) |
| removeListener(type, handle) | Remove a listener |
| subscribe(handle, once?) | Subscribe to all events |
| unsubscribe(handle) | Cancel a subscription |
| dispatch(evt) | Dispatch an event |
| emit(evt) | Dispatch an event (alias of dispatch) |
| listenerCount(type?) | Get listener count |
| cleanup() | Remove all listeners and subscribers |
| dispose() | Dispose the event bus |
| registerDisposable(disposable) | Register a disposable to be disposed with the bus |
