The @esmj/emitter
is tiny (O,9kB) async event emitter library.
It works in Node.js and the browser (using a bundler like webpack).
- Node 18+
npm install @esmj/emitter
It works for both Javascript modules (ESM and CJS).
import { Emitter } from '@esmj/emitter';
const emitter = new Emitter();
emitter.on('some-event', async (event) => {
return 2 * event.result;
});
emitter.on('some-event', (event) => {
return 3 * event.result;
});
emitter.on('some-event', (event) => {
event.stopPropagation();
});
emitter.on('some-event', async (event) => {
return 4 * event.result;
});
const { result } = await emitter.emit('some-event', { result: 1 });
console.log(result); // 6
Or if you want to use custom name for result from your listeners. You can use RESULT_KEY
symbol as example below.
import { Emitter, RESULT_KEY } from '@esmj/emitter';
const emitter = new Emitter();
emitter.on('some-event', async (event) => {
return 2 * event.count;
});
emitter.on('some-event', (event) => {
return 3 * event.count;
});
emitter.on('some-event', (event) => {
event.stopPropagation();
});
emitter.on('some-event', async (event) => {
return 4 * event.count;
});
const { count } = await emitter.emit('some-event', { count: 1, [RESULT_KEY]: 'count' });
console.log(count); // 6
Create a new instance of Emitter.
Type: object
Configure the new instance of Emitter.
Type: object
Default: console
Configure the logger for this instance.
Type: boolean|function(eventName, event)
Default: false
Configure the debugging options for this instance.
Subscribe listener for event.
Returns an unsubscribe method.
Remove subscription.
Subscribe event for listener only once. It will be unsubscribed after the first call.
Trigger an event asynchronously/synchronously. It is depends on returns value from listener. Listeners are called in the order they were added and executed serially.
Trigger an event asynchronously in parallel. The listeners for the event will be executed concurrently and when the listeners are not dependent on each other.
Returns a promise that resolves with an event, which has result an array of results from the event listeners. The promise is rejected if one of the listeners throws an error.
import { Emitter } from '@esmj/emitter';
const emitter = new Emitter();
emitter.on('some-event', async (event) => {
return 2 * event.count;
});
emitter.on('some-event', (event) => {
return 3 * event.count;
});
emitter.on('some-event', () => {});
emitter.on('some-event', async (event) => {
return 4 * event.count;
});
const { counts } = await emitter.emitParallel('some-event', { count: 1, RESULT_KEY: 'counts' });
console.log(counts); // [2, 3, undefined, 4]