eventin
v2.0.4
Published
Strongly-typed event emitter.
Downloads
14
Readme
eventin
Strongly-typed event emitter.
Install & Usage
npm install eventin
import Eventin from 'eventin';
enum EventType {
OPEN = 'open',
CLOSE = 'close',
TOGGLE = 'toggle',
}
const e = new Eventin<
EventType,
{
[EventType.OPEN]: { id: string };
[EventType.CLOSE]: { source: number };
[EventType.TOGGLE]: boolean;
}
>();
const unlisten = e.listen(EventType.OPEN, ({ id }) => console.log(id));
const unlisten = e.listen(EventType.OPEN, ({ source }) => console.log(source)); // it will throw typescript error
e.emit(EventType.OPEN, { id: 'eventin' });
e.emit(EventType.OPEN, 123); // it will throw typescript error
/** listen once */
const unlisten = e.listen(EventType.OPEN, ({ id }) => console.log(id), {
once: true,
});
/** trigger listener synchronously */
e.emit(EventType.OPEN, { id: 'eventin' }, { sync: true });
/** unlistenAll */
e.unlistenAll(EventType.OPEN);
e.unlistenAll();
Also you can use e.unlisten
to remove a listener:
import Eventin, { Listener } from 'eventin';
enum EventType {
OPEN = 'open',
CLOSE = 'close',
TOGGLE = 'toggle',
}
type EventTypeMapData = {
[EventType.OPEN]: { id: string };
[EventType.CLOSE]: { source: number };
[EventType.TOGGLE]: boolean;
};
const e = new Eventin<EventType, EventTypeMapData>();
// (data: { id: string }) => void
type OpenListener = Listener<EventType, EventTypeMapData, EventType.OPEN>;
const openListener: OpenListener = (data) => console.log(data);
e.listen(EventType.OPEN, openListener);
e.unlisten(EventType.OPEN, openListener);