signal-ts
TypeScript icon, indicating that this package has built-in type declarations

1.2.4 • Public • Published

Build Status npm version

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(nnumber) => {
    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);

License

MIT License

Package Sidebar

Install

npm i signal-ts

Weekly Downloads

5

Version

1.2.4

License

MIT

Unpacked Size

6.64 kB

Total Files

6

Last publish

Collaborators

  • polyglot