Simple and modern async event emitter
It works in Node.js and the browser (using a bundler).
Emitting events asynchronously is important for production code where you want the least amount of synchronous operations. Since JavaScript is single-threaded, no other code can run while doing synchronous operations. For Node.js, that means it will block other requests, defeating the strength of the platform, which is scalability through async. In the browser, a synchronous operation could potentially cause lags and block user interaction.
$ npm install emittery
const Emittery = require('emittery');
const emitter = new Emittery();
emitter.on('๐ฆ', data => {
console.log(data);
});
const myUnicorn = Symbol('๐ฆ');
emitter.on(myUnicorn, data => {
console.log(`Unicorns love ${data}`);
});
emitter.emit('๐ฆ', '๐'); // Will trigger printing '๐'
emitter.emit(myUnicorn, '๐ฆ'); // Will trigger printing 'Unicorns love ๐ฆ'
Emittery accepts strings and symbols as event names.
Symbol event names can be used to avoid name collisions when your classes are extended, especially for internal events.
Subscribe to one or more events.
Returns an unsubscribe method.
Using the same listener multiple times for the same event will result in only one method call per emitted event.
const Emittery = require('emittery');
const emitter = new Emittery();
emitter.on('๐ฆ', data => {
console.log(data);
});
emitter.on(['๐ฆ', '๐ถ'], data => {
console.log(data);
});
emitter.emit('๐ฆ', '๐'); // log => '๐' x2
emitter.emit('๐ถ', '๐'); // log => '๐'
Emittery exports some symbols which represent custom events that can be passed to Emitter.on
and similar methods.
Emittery.listenerAdded
- Fires when an event listener was added.Emittery.listenerRemoved
- Fires when an event listener was removed.
const Emittery = require('emittery');
const emitter = new Emittery();
emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
console.log(listener);
//=> data => {}
console.log(eventName);
//=> '๐ฆ'
});
emitter.on('๐ฆ', data => {
// Handle data
});
listener
- The listener that was added.eventName
- The name of the event that was added or removed if.on()
or.off()
was used, orundefined
if.onAny()
or.offAny()
was used.
Only events that are not of this type are able to trigger these events.
Remove one or more event subscriptions.
const Emittery = require('emittery');
const emitter = new Emittery();
const listener = data => console.log(data);
(async () => {
emitter.on(['๐ฆ', '๐ถ', '๐ฆ'], listener);
await emitter.emit('๐ฆ', 'a');
await emitter.emit('๐ถ', 'b');
await emitter.emit('๐ฆ', 'c');
emitter.off('๐ฆ', listener);
emitter.off(['๐ถ', '๐ฆ'], listener);
await emitter.emit('๐ฆ', 'a'); // nothing happens
await emitter.emit('๐ถ', 'b'); // nothing happens
await emitter.emit('๐ฆ', 'c'); // nothing happens
})();
Subscribe to one or more events only once. It will be unsubscribed after the first event.
Returns a promise for the event data when eventName
is emitted.
const Emittery = require('emittery');
const emitter = new Emittery();
emitter.once('๐ฆ').then(data => {
console.log(data);
//=> '๐'
});
emitter.once(['๐ฆ', '๐ถ']).then(data => {
console.log(data);
});
emitter.emit('๐ฆ', '๐'); // log => '๐' x2
emitter.emit('๐ถ', '๐'); // nothing happens
Get an async iterator which buffers data each time an event is emitted.
Call return()
on the iterator to remove the subscription.
const Emittery = require('emittery');
const emitter = new Emittery();
const iterator = emitter.events('๐ฆ');
emitter.emit('๐ฆ', '๐1'); // Buffered
emitter.emit('๐ฆ', '๐2'); // Buffered
iterator
.next()
.then(({value, done}) => {
// done === false
// value === '๐1'
return iterator.next();
})
.then(({value, done}) => {
// done === false
// value === '๐2'
// Revoke subscription
return iterator.return();
})
.then(({done}) => {
// done === true
});
In practice, you would usually consume the events using the for await statement. In that case, to revoke the subscription simply break the loop.
const Emittery = require('emittery');
const emitter = new Emittery();
const iterator = emitter.events('๐ฆ');
emitter.emit('๐ฆ', '๐1'); // Buffered
emitter.emit('๐ฆ', '๐2'); // Buffered
// In an async context.
for await (const data of iterator) {
if (data === '๐2') {
break; // Revoke the subscription when we see the value '๐2'.
}
}
It accepts multiple event names.
const Emittery = require('emittery');
const emitter = new Emittery();
const iterator = emitter.events(['๐ฆ', '๐ฆ']);
emitter.emit('๐ฆ', '๐1'); // Buffered
emitter.emit('๐ฆ', '๐2'); // Buffered
iterator
.next()
.then(({value, done}) => {
// done === false
// value === '๐1'
return iterator.next();
})
.then(({value, done}) => {
// done === false
// value === '๐2'
// Revoke subscription
return iterator.return();
})
.then(({done}) => {
// done === true
});
Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
Returns a promise that resolves when all the event listeners are done. Done meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
Same as above, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer emit()
whenever possible.
If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will not be called.
Subscribe to be notified about any event.
Returns a method to unsubscribe.
Remove an onAny
subscription.
Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.
Call return()
on the iterator to remove the subscription.
const Emittery = require('emittery');
const emitter = new Emittery();
const iterator = emitter.anyEvent();
emitter.emit('๐ฆ', '๐1'); // Buffered
emitter.emit('๐', '๐2'); // Buffered
iterator.next()
.then(({value, done}) => {
// done === false
// value is ['๐ฆ', '๐1']
return iterator.next();
})
.then(({value, done}) => {
// done === false
// value is ['๐', '๐2']
// Revoke subscription
return iterator.return();
})
.then(({done}) => {
// done === true
});
In the same way as for events
, you can subscribe by using the for await
statement
Clear all event listeners on the instance.
If eventNames
is given, only the listeners for that events are cleared.
The number of listeners for the eventNames
or all events if not specified.
Bind the given methodNames
, or all Emittery
methods if methodNames
is not defined, into the target
object.
import Emittery = require('emittery');
const object = {};
new Emittery().bindMethods(object);
object.emit('event');
The default Emittery
class does not let you type allowed event names and their associated data. However, you can use Emittery.Typed
with generics:
import Emittery = require('emittery');
const emitter = new Emittery.Typed<{value: string}, 'open' | 'close'>();
emitter.emit('open');
emitter.emit('value', 'foo\n');
emitter.emit('value', 1); // TS compilation error
emitter.emit('end'); // TS compilation error
A decorator which mixins Emittery
as property emitteryPropertyName
and methodNames
, or all Emittery
methods if methodNames
is not defined, into the target class.
import Emittery = require('emittery');
@Emittery.mixin('emittery')
class MyClass {}
const instance = new MyClass();
instance.emit('event');
Listeners are not invoked for events emitted before the listener was added. Removing a listener will prevent that listener from being invoked, even if events are in the process of being (asynchronously!) emitted. This also applies to .clearListeners()
, which removes all listeners. Listeners will be called in the order they were added. So-called any listeners are called after event-specific listeners.
Note that when using .emitSerial()
, a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.
There are many things to not like about EventEmitter
: its huge API surface, synchronous event emitting, magic error event, flawed memory leak detection. Emittery has none of that.
Mostly backwards compatibility reasons. The Node.js team can't break the whole ecosystem.
It also allows silly code like this:
let unicorn = false;
emitter.on('๐ฆ', () => {
unicorn = true;
});
emitter.emit('๐ฆ');
console.log(unicorn);
//=> true
But I would argue doing that shows a deeper lack of Node.js and async comprehension and is not something we should optimize for. The benefit of async emitting is much greater.
No, just use destructuring:
emitter.on('๐ฆ', ([foo, bar]) => {
console.log(foo, bar);
});
emitter.emit('๐ฆ', [foo, bar]);
- p-event - Promisify an event by waiting for it to be emitted