A lightweight typesafe event emitter with zero dependencies.
npm install ts-events-emitter
import { createEventEmitter } from "ts-events-emitter";
type TEvent = {
"event-one": { a: number; b: string };
"event-two": { c: number; d: string };
};
const emitter = createEventEmitter<TEvent>();
emitter.on("event-one", (event) => {
console.log(event.a);
});
emitter.emit("event-one", { a: 100, b: "hello" });
emitter.emit("event-one", { a: 1, b: "foo" });
emitter.on("event-one", (event) => {
console.log(event.a);
});
emit: <P extends keyof T>(event: P, message: T[P]) => void;
on: <P extends keyof T>(event: P, callback: (message: T[P]) => void) => void;
once: <P extends keyof T>(event: P,callback: (message: T[P]) => void) => void;
off: <P extends keyof T>(event: P,callback: (message: T[P]) => void) => void;
offAll: (event: keyof T) => void;