#
EventBus
A basic implementation of a pub/sub mechanism enabling loosely coupled between the host application and the modules.
#
Reference
const eventBus = new EventBus(options?: { logger? })
#
Parameters
options
: An optional object literal of options:logger
: An optional logger to facilitate debugging.
#
Methods
addListener(eventName, callback, options?)
: Register thecallback
event listener foreventName
.removeListener(eventName, callback, options?)
: Remove thecallback
event listener foreventName
.dispatch(eventName, payload?)
: Dispatch an event to the listeners ofeventName
.
#
Usage
#
Create an event bus instance
import { EventBus, RuntimeLogger } from "@squide/firefly";
const eventBus = new EventBus({
logger: new RuntimeLogger([])
});
#
Add a listener
When possible, prefer useEventBusListener to eventBus.addListener
.
import { useCallback } from "react";
const handleFoo = useCallback((data, context) => {
// do something...
}, [];
// Listen to every "foo" events.
eventBus.addListener("foo", handleFoo);
// Listen to the first "foo" event, then automatically remove the listener.
eventBus.addListener("foo-once", handleFoo, { once: true });
#
Remove a listener
// Remove a regular listener.
eventBus.removeListener("foo", handleFoo);
// Remove a listener created with the `once` option.
eventBus.removeListener("foo-once", handleFoo, { once: true });
#
Dispatch an event
When possible, prefer useEventBusDispatcher to eventBus.dispatch
.
eventBus.dispatch("foo", "bar");