Currently, I am working on developing a TypeScript game and facing some challenges with adding and removing a "keydown" event. The event function is currently referencing the document when I actually need it to refer to the object instance.
Is there a way to achieve this?
class Player {
board: Board = new Board();
pice: Pice = new Pice();
constructor() {
this.registerKeyEvents();
}
registerKeyEvents(): void {
document.addEventListener("keydown", this.handleKeyPress);
}
unregisterKeyEvents(): void {
document.removeEventListener("keydown", this.handleKeyPress);
}
handleKeyPress(event: KeyboardEvent): void {
console.log(this); // #document
switch (event.keyCode) {
// Left
case 37:
this.pice.move(-1, 0, this.board);
break;
}
}
}