event-emitter-typesafe
This package is meant to give you an easy to use way of defining an event emitter which is typesafe. Those definitions
can be either applied by mixin or by extension of the EventEmitter
class.
In either way those classes offer the three main methods add
, remove
and dispatch
and several alias. The API
documentation is available at: https://feirell.github.io/event-emitter-typesafe/.
usage
extending
The easiest way is to just extend the provided EventEmitter
.
import {EventEmitter} from "event-emitter-typesafe";
interface ExampleEvents {
'example-a': { data: number },
'example-b': { data: number },
'example-c': { data: number },
'example-d': { data: number }
}
class Example extends EventEmitter<ExampleEvents> {
}
const e = new Example();
e.once('example-c', () => console.log('example c was emitted'));
e.addEventListener('example-c', (ev) => console.log(ev.data));
e.emit('example-c', {data: 12});
e.dispatch('example-c', {data: 42});
e.on('example-a', () => { });
You can find this in examples\example-extending.ts
mixin
You can also use the second option which leverages TypeScript mixins which allow you to provide the functionality off
the EventEmitter
without extending it. This can be useful if you already are extending another class.
Mixins results in pretty much the same type situation as you would have with extension.
import {EventEmitterInt, makeEventEmitter} from "event-emitter-typesafe";
class SomeOtherClass {}
class Example extends SomeOtherClass {}
interface ExampleEvents {
'example-a': { data: number },
'example-b': { data: number },
'example-c': { data: number },
'example-d': { data: number }
}
interface Example extends EventEmitterInt<ExampleEvents> {}
makeEventEmitter(Example);
const e = new Example();
e.addEventListener('example-c', (ev) => console.log(ev.data));
e.dispatch('example-c', {data: 12});
You can find this in examples\example-mixin.ts
standalone
You could always just create an instance of the EventEmitter
instead of extending it.
similar
The package @servie/events is quite similar but does not provide a mixin
option and some of the alias.