@horyzont85/typed-event-emitter
Typed Event Emitter
Last updated 5 months ago by horyzont85 .
apache-2.0 · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install @horyzont85/typed-event-emitter 
SYNC missed versions from official npm registry.

typed-event-emitter

Here we have some examples of usage:

Simple Emitting and Observing

interface MyEvents {
    RESPONSE: (message: string, code: number) => void;
    CLICK: () => void;
}

let emitter = new TypedEventEmitter<MyEvents>();

// OK, proper parameters' type
emitter.on("RESPONSE", (message: string, code: number) => {
    console.log(`Message: ${message}, code: ${code}`);
});

// OK, proper parameters' type
emitter.emit("RESPONSE", "New response", 400);

// type error, FOO is not type of event
emitter.on("FOO", (message: string, code: number) => {
    console.log(`Message: ${message}, code: ${code}`);
});

// type error, message type is string not number
emitter.on("RESPONSE", (message: number, code: number) => {
    console.log(`Message: ${message}, code: ${code}`);
});

// type error, FOO is not type of event
emitter.emit("FOO", "New response", 400);

// type error, code type is number not string
emitter.emit("RESPONSE", "New response", "400");

Using Typed Event Emitter as a base class

interface MyModel {
    name: string;
    surname: string;
    age: number;
}

interface MyEvents {
    CLICK: (model: MyModel) => void;
}

class MyController extends TypedEventEmitter<MyEvents> {
    constructor() {
        super();
    }

    public emitEvent() {
        this.emit("CLICK", {age: 20, name: "Piotr", surname: "Burning Water"});
    }
}

interface YourEvents {
    RESPONSE: (response: number) => void;
}

class YourController extends TypedEventEmitter<YourEvents> {

    // no possibility to emit events from MyController
    constructor(private myController: Observer<MyEvents>) {
        super();
        this.myController.on("CLICK", (model: MyModel) => {
            console.log(model);
        });
    }
}

let firstController = new MyController();
new YourController(firstController);
firstController.emitEvent();

Current Tags

  • 1.0.5                                ...           latest (5 months ago)

1 Versions

  • 1.0.5                                ...           5 months ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 3
Dependencies (3)
Dev Dependencies (9)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |