signal-ts
v1.2.4
Published
Simple to use Signal pattern written in Typescript. Signals are typed.
Downloads
5
Maintainers
Readme
TypeScript Signal
Signal Pattern pattern written in Typescript.
Signals are typed and easy to use!
Installation
npm install signal-ts
Usage
Creating a Signal
Create an instance of Signal with the specified type, i.e, string, number, etc.
import {Signal} from "signal-ts";
let onCompleted: Signal<number> = new Signal();
Add function callback
Register a callback with add().
onCompleted.add((n: number) => {
console.log("got a number", n);
});
You can also register a callback only once().
onCompleted.once(n: number) => {
console.log("got a number once", n);
});
Emitting a Signal
onCompleted.emit(299792458);
Pro-Tips
Organize your events in a module or namespace.
export namespace Event {
export const onLoaded: Signal<string> = new Signal();
export const onCompleted: Signal<number> = new Signal();
}
Bind to events in your constructor.
class Receiver {
private message: string;
constructor() {
Event.onLoaded.add(this.loaded);
}
public loaded(message: string): void {
this.message = message;
}
}
Remove a callback
Event.onLoaded.remove(this.callback);