0.4.0 • Published 2 years ago
@susisu/tyde v0.4.0
@susisu/tyde
Typed event emitter
Installation
# npm
npm i @susisu/tyde
# yarn
yarn add @susisu/tyde
# pnpm
pnpm add @susisu/tydeUsage
tyde provides API that is similar to EventEmitter and event-kit.
The simplest usage is subscribing events with .on() and emitting events with .emit().
import { Emitter } from "@susisu/tyde";
const emitter = new Emitter();
const subscription = emitter.on("change", value => {
  console.log(value);
});
emitter.emit("change", 42); // -> 42Subscriptions can be unsubscribed by calling .unsubscribe().
subscription.unsubscribe();
emitter.emit("change", 0); // no outputThe curried version of .on() is also available.
const onChange = emitter.on("change");
const subscription = onChange(value => { /* ... */ });You can optionally restrict types of emitted values by giving a dictionary to Emitter's type parameter.
const emitter = new Emitter<{
  "change": number,
  "destroy": void,
}>();
emitter.emit("change", 42);     // ok
emitter.emit("destroy");        // ok
emitter.emit("foo", 42);        // type error: unknown event
emitter.emit("change", "test"); // type error: mismatched typeDifference from other event emitters
By design, tyde has some difference from other event emitter libraries:
- No wildcards, because of the strongly typed interface.
- Events are emitted asynchronously by default.- Usually event handlers should not care whether it is called synchronously or asynchronously.
- There is also a synchronous version .emitSync(), but it is not generally recommended.
 
- Invocation order of event handlers is not guaranteed in any way.- Specifying execution order in a less explicit way will lower the readability of code.
- If you still want one, invoke functions sequentially in one event handler, or separate the event into multiple stages.