1.1.0 • Published 2 years ago

simple-typed-events v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

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);
1.1.0

2 years ago

1.0.11

2 years ago

1.0.10

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago