【发布时间】:2019-01-11 20:20:54
【问题描述】:
我试图弄清楚如何在 TypeScript 中为类创建自定义事件。像this one 这样的例子对我理解如何做到这一点没有多大帮助。
我的示例类如下所示。
猫.ts:
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");
}
}
现在我希望能够从外部声明事件,就像下面的代码旨在演示的那样。
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();
现在,我想得到一些像这样的输出:
onWillMeow
Tikki the cat is just about to meow!
Cat meows!
onDidMeow
Tikki the cat did just meow!
我必须做什么才能在 TypeScript 中完成这项工作?这个具体怎么称呼?创建自定义事件还是创建自定义事件处理程序?
【问题讨论】:
标签: typescript events event-handling