interface GameEvent {
gameStarted(name: string): void
}
class Game {
public name: string
private _listeners: GameEvent[]
constructor(name: string) {
this.name = name;
this._listeners = [];
}
addListener(listener: GameEvent) {
this._listeners.push(listener);
}
start() {
for (let listener of this._listeners) {
listener.gameStarted(this.name);
}
}
}
class Statistic implements GameEvent {
public startsCount: number = 0
public lastGame: string = ""
gameStarted(name: string) {
this.startsCount++;
this.lastGame = name;
}
}
let statistic = new Statistic()
let heroes = new Game("Heroes")
let doom = new Game("Doom")
//subscribe to events
heroes.addListener(statistic)
doom.addListener(statistic)
doom.start()
heroes.start()
//statistic.lastGame is "Heroes"
//statistic.startsCount is 2
console.log("lastGame is",
statistic.lastGame)
console.log("startsCount is",
statistic.startsCount)