simple-typed-events
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

simple-typed-events

npm codecov

Simple event emitter interface with full TypeScript support. Simply define your event names and their callbacks in an interface and pass it to createEventEmitter as a generic arg.


Function list:

  • createEventEmitter<T>() - returns an object with 4 functions
    • on - Attach event listener
    • off - Detach event listener
    • once - Attach an event listener that will only fire once
    • emit - Emit an event
import { createEventEmitter } from 'simple-typed-events';

interface Events {
  start: () => void;
  progress: (loaded: number, total: number) => void;
  finish: () => void;
}

const emitter = createEventEmitter<Events>();

// attach event listener with on()
emitter.on('start', () => {});

// the Events interface can be used as a lookup type
const onProgress: Events['progress'] = (loaded, total) => {
  // ...
};

emitter.on('progress', onProgress);
emitter.on('progress', (loaded, total) => {
  // ...
});

emitter.once('finish', () => {
  // ...
});

emitter.emit('progress'); // Typescript error! the args of the progress event must be passed
emitter.emit('progress', 3); // Still not legal. Both args must be passed
emitter.emit('progress', 3, 5); // no error

// detach listeners by reference
emitter.off('progress', onProgress);

Package Sidebar

Install

npm i simple-typed-events

Weekly Downloads

1

Version

1.1.0

License

MIT

Unpacked Size

21.9 kB

Total Files

12

Last publish

Collaborators

  • bsssshhhhhhh