我正在尝试了解如何为 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 中完成这项工作?这到底是怎么称呼的?创建自定义事件或创建自定义事件处理程序?
最佳答案
像这样:
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();
我确信有图书馆可以提供帮助。有人想在另一个答案中推荐一个图书馆吗?
关于typescript - 在 TypeScript 类中创建自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51681107/