在TypeScript的类内创建自定义事件

Soc*_*tes 3 events event-handling typescript

我试图弄清楚如何为TypeScript中的类创建自定义事件。像这样的例子并不能帮助我理解如何做。

我的示例类如下所示。

类别:

export class Cat {
    public getName(): string {
        return this.catName;
    }

    public setName(catName: string) {
        this.catName = catName;
    }

    constructor(private catName: string) { }

    public makeMeow() {
        this.onWillMeow();
        console.log("Cat meows!");
        this.onDidMeow();
    }

    public onWillMeow() {
        console.log("onWillMeow");
    }

    public onDidMeow() {
        console.log("onDidMeow");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够从外部声明事件,如以下代码旨在演示。

const myCat: Cat = new Cat("Tikki");
myCat.onWillMeow({event => {
     console.log("Tikki the cat is just about to meow!");
}});
myCat.onWillMeow({event => {
     console.log("Tikki the cat did just meow!");
}});
myCat.makeMeow();
Run Code Online (Sandbox Code Playgroud)

现在,我想得到这样的输出:

onWillMeow
Tikki the cat is just about to meow!
Cat meows!
onDidMeow
Tikki the cat did just meow!
Run Code Online (Sandbox Code Playgroud)

我要做什么才能在TypeScript中完成这项工作?究竟如何称呼它?创建自定义事件还是创建自定义事件处理程序

Mat*_*hen 6

像这样:

type Handler<E> = (event: E) => void;

class EventDispatcher<E> { 
    private handlers: Handler<E>[] = [];
    fire(event: E) { 
        for (let h of this.handlers)
            h(event);
    }
    register(handler: Handler<E>) { 
        this.handlers.push(handler);
    }
}

interface WillMeowEvent { }
interface DidMeowEvent { }

class Cat {
    public getName(): string {
        return this.catName;
    }

    public setName(catName: string) {
        this.catName = catName;
    }

    constructor(private catName: string) { }

    public makeMeow() {
        this.fireWillMeow({});
        console.log("Cat meows!");
        this.fireDidMeow({});
    }

    private willMeowDispatcher = new EventDispatcher<WillMeowEvent>();
    public onWillMeow(handler: Handler<WillMeowEvent>) {
        this.willMeowDispatcher.register(handler);
    }
    private fireWillMeow(event: WillMeowEvent) { 
        console.log("onWillMeow");
        this.willMeowDispatcher.fire(event);
    }

    private didMeowDispatcher = new EventDispatcher<DidMeowEvent>();
    public onDidMeow(handler: Handler<DidMeowEvent>) {
        this.didMeowDispatcher.register(handler);
    }
    private fireDidMeow(event: DidMeowEvent) { 
        console.log("onDidMeow");
        this.didMeowDispatcher.fire(event);
    }
}

const myCat: Cat = new Cat("Tikki");
myCat.onWillMeow(event => {
     console.log("Tikki the cat is just about to meow!");
});
myCat.onDidMeow(event => {
     console.log("Tikki the cat did just meow!");
});
myCat.makeMeow();
Run Code Online (Sandbox Code Playgroud)

我确定有可以帮助您的库。任何人都想在另一个答案中推荐图书馆吗?