0.0.1 • Published 7 months ago

@2k/ee v0.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

EE (Event Emitter)

Tiny, typed event emitter utility for Node.js and browsers. No dependencies.

Need a single event and type, only? Use Signal instead

Installation

npm install @2k/ee --save

Usage (TypeScript)

import { EE } from '@2k/ee';

// map event names to their callback param types
interface Events {
  a: number;
  b: string;
  c: undefined;
}

const ee = new EE<Events>();

const cb = (num: number) => console.log('A', num);

ee.on('a', cb);
ee.on('b', str => console.log('B', str));
ee.once('c', () => console.log('C'));

ee.emit('a', 123);
ee.emit('b', 'hello');
ee.emit('c');

ee.off('a', cb);

ee.event('b', 123); // error
ee.event('d', 123); // error

Methods

on(event, fn)

Attaches an event handler to be called whenever the event fires.

once(event, fn)

Attaches a one-time handler which is unbound after it fires the first time.

off(event, fn?)

Detaches one instance of a given handler from the event emitter. If no handler is provided, detaches all handlers.

emit(event, arg)

Fires the event synchronously, triggering any attached handlers with the given arg.

event(event, arg)

Fires the event asynchronously, triggering any attached handlers with the given arg. Useful when attaching handlers later in the same event loop turn.