I am trying to figure out how to create a custom event for a class in TypeScript. Examples like this one didn't help me much in understanding how to do that.
My example class looks like the following.
Cat.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");
}
}
Now I would like to be able to declare events from outside like the following code aims to demonstrate.
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();
Now, I would imagine to get some output like this one:
onWillMeow
Tikki the cat is just about to meow!
Cat meows!
onDidMeow
Tikki the cat did just meow!
What do I have to do to make this work in TypeScript? How is this called exactly? Creating a custom event or creating a custom event handler?