- inspiration with the Vue2
event-bus pattern
npm i --save @petr-ptacek/event-bus
import { EventBus } from "@petr-ptacek/event-bus";
const eb = new EventBus<{
sum: (a: number, b: number) => void;
}>();
eb.on("sum", (a, b) => {
console.log(`recieved: ${ a } ${ b }`);
});
eb.emit("sum", 1, 2);
Called when the event type is emitted.
interface OnFn {
(type: string, handler: Function);
}
const eb = new EventBus();
eb.on("sum", (...args) => {
/*...*/
});
Called only once, then the handler is unregistered.
interface OnceFn {
(type: string, handler: Function);
}
const eb = new EventBus();
eb.once("sum", (...args) => {
/*...*/
});
Unregister handler/s. If the handler reference is not provided, unregister all handlers by that type.
interface OffFn {
(type: string, handler?: Function);
}
function sum(a: number, b: number) {
}
const eb = new EventBus();
eb.off("sum", sum);
Emit the correct type with provided arguments.
interface EmitFn {
(type: string, ...args: any[]);
}
function sum(a: number, b: number) {
}
const eb = new EventBus();
eb.on("sum", sum);
eb.emit("sum", 1, 1);