Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

simple-event-target

fregante20.5kMIT2.1.0TypeScript support: included

Thinnest possible wrapper around native events. It simplifies typing the custom event detail

event target, event emitter, emitter, typescript, event

readme

simple-event-target

Thinnest possible wrapper around native events. It simplifies typing the custom event detail.

Install

npm install simple-event-target

Usage

import SimpleEventTarget from 'simple-event-target';

type Info = {level: 'light' | 'golden' | 'coal'};
const toasts = new SimpleEventTarget<Info>();

toasts.subscribe(info => {
    console.log('Toast popped as', info.level);
})

toasts.emit({level: 'golden'});

API

SimpleEventTarget

Creates the event target:

const toasts = new SimpleEventTarget();

In TypeScript you can also specify the event contents type if used:

type Info = {level: 'light' | 'golden' | 'coal'};
const toasts = new SimpleEventTarget<Info>();

SimpleEventTarget#subscribe(listener)

Adds a listener to the target, the listener will be called with the emitted value.

Calling it multiple times with the same listener will not add it multiple times, just like the native EventTarget.

toasts.subscribe(spread => console.log(`You’ve got a ${spread} toast`));

SimpleEventTarget#unsubscribe(listener)

Removes a previously-added listener from the target.

const listener = spread => console.log(`You’ve got a ${spread} toast`);
toasts.subscribe(listener);
toasts.unsubscribe(listener);

SimpleEventTarget#emit(value)

Calls all the registered listener by passing the value as the main argument:

toasts.subscribe(console.log);
toasts.emit('Jam');
// -> logs 'Jam'

Error handling is the same as using dispatchEvent on EventTarget.

SimpleEventTarget#raw

Sometimes you might want to access the underlying EventTarget instance:

toasts.raw.eventTarget.addEventListener(toasts.raw.eventType, event => {
    console.log('This is the real event object', event);
});

Note that dispatching events or listening to events directly circumvents the type safety of the SimpleEventTarget wrapper.

License

MIT © Federico Brigante