A lightweight, flexible event bus for JavaScript/TypeScript. Supports any type of event identifier, wildcard event names, and listener capacity control. You can even get an id from eventBus.on and get emit result from eventBus.emit!
For more awesome packages, check out my homepage💛
pnpm add wildcard-event
# or
npm install wildcard-eventimport { eventBus } from 'wildcard-event';
// Wildcard support
eventBus.on('user.*', () => console.log('Any user event!'));
eventBus.emit('user.logout'); // triggers wildcard
// Emit
const emitResult = eventBus.emit('user.login', { name: 'Alice' });
// Set the name of the eventBus
eventBus.name; // it is readonly
eventBus.setName('MyEventBus'); // eventBus.name is now 'MyEventBus'emit method now returns an object(interface: EmitResult). With the identifier-listener entry id, you can get the specific handler result if you want to.
// save the unique 'identifier-listener' id returned from `on` method
const listener = (user) => {
console.log('User logged in:', user);
};
const id = eventBus.on('user.*', listener);
// emit an event and receive its result
const emitResult = eventBus.emit('user.login', { name: 'Alice' });Then the emitResult will look like this:
expect(emitResult).toEqual({
ids: [id], // array of listener ids that were triggered
[id]: {
identifier: 'user.*', // the matched identifier when it was registered
result: listener({ name: 'Alice' }), // result of the listener
rest: Infinity, // remaining capacity (if set)
},
});Note: The listener can be an async function, which makes
emitResult[someId].resulta Promise.
Register a listener for an event. identifier can be any value. capacity (optional) limits how many times the listener can be triggered.
- Default
capacityisInfinity. - When emitting, the listeners will be called in the order they were registered.
Register a listener that will be triggered only once.
Remove all listeners for the given event identifier.
Remove a specific listener by its id (returned from on/once).
Trigger an event. Returns null if no listener is found, or an object with results and remaining capacity.
*matches a single segment (e.g.user.*matchesuser.login, notuser.profile.update)**matches multiple segments (e.g.user.**matchesuser.login,user.profile.update,user.settings.privacy.change, anduseritself)- Cannot use both
**and*in the same identifier - Cannot use more than 2
*s, like***or more - Cannot start or end with a dot (
.). - Mixed:
user.*.settingsmatchesuser.admin.settings,user.guest.settings - Only registration (on/once) supports wildcards; emit must use concrete event names
type Fn = (...args: unknown[]) => unknown;
interface EventConfig {
listener: Fn;
capacity: number;
}
interface EmitResultValue {
identifier: unknown;
result: unknown;
rest: number;
}
interface EmitResult {
ids: number[];
[key: number]: EmitResultValue;
}Kasukabe Tsumugi
futami16237@gmail.com
Enjoy! (づ。◕‿‿◕。)づ
