ts-event-emitter
(yet another) event emitter written in typescript 😔
Installation
npm install @dominicstop/ts-event-emitter
yarn add @dominicstop/ts-event-emitter
Usage
Basic Usage
type EventKeys = 'Foo' | 'Baz';
export const emitter: TSEventEmitter<EventKeys, {
Foo: string;
Baz: { age: number } | null;
}> = new TSEventEmitter();
emitter.once('Foo', (event) => { console.log(event) });
emitter.emit('Foo', 'hello world');
emitter.once('Baz', (event) => { console.log(event?.age) });
emitter.emit('Baz', { age: 23 });
In-Depth Usage
enum Events { Foo = 'Foo', Bar = 'Bar', Baz = 'Baz' };
type EventKeys = 'Foo' | 'Bar' | 'Baz';
export const emitter: TSEventEmitter<EventKeys, {
Foo: { name: string },
Bar: null,
Baz: null | { age: number }
}> = new TSEventEmitter();
emitter.once('Foo', (event) => { console.log(event.name) });
emitter.once('Bar', () => { });
emitter.once(Events.Baz, (event) => { console.log(event?.age) });
emitter.emit(Events.Foo, { name: 'd'});
emitter.emit('Baz', { age: 1 });
emitter.emit('Bar');
emitter.emit('Baz', null);
Documentation
TSEvenEmitter
Property/Method | Description |
---|
🔤 addListener
⚛️ (eventKey, listener) => { unsubscribe: () => void } | |
🔤 removeListener
⚛️ (eventKey, listenerToRemove) => void | |
🔤 once
⚛️ (eventKey, listener) => void | |
🔤 removeAllListeners
⚛️ () => void | |
🔤 emit
⚛️ (eventKey, data) => void | |