@garzj/event-subscriber
v2.0.0
Published
An event proxy allowing for easy removal of subscriptions on the EventEmitter class
Downloads
34
Readme
@garzj/event-subscriber
Proxies subscriptions to an EventEmitter and stores references, allowing for an easy removal.
Features
- TypeScript support
- Compatible with
Heads up
Due to a TypeScript limitation (there does not seem to be a reliable way to remap return types of function overloads), methods of the EventSubscriber
class may look like they return the original event emitter (they do not, the subscriber is returned).
It's probably better to avoid chaines like .on(a, b).on(c, d)
and prefer sub.on(a, b); sub.on(c, d);
instead.
Installation
npm i @garzj/event-subscriber
Usage
import { EventEmitter } from 'events';
import { EventSubscriber } from '@garzj/event-subscriber';
const myEmitter = new EventEmitter();
myEmitter.on('my-event', () => console.log('Always called!'));
myEmitter.emit('my-event');
const sub = new EventSubscriber(myEmitter);
sub.on('my-event', () => console.log('Temporarily called!'));
myEmitter.emit('my-event');
sub.off();
myEmitter.emit('my-event');
Output
Always called!
Always called!
Temporarily called!
Always called!