0

I am making this game in TypeScript, and trying to add and remove a "keydown" event. The event function is referring to "this", witch is the document, but i am trying to refer to the object instance.

How can this be achieved?

class Player {
    board: Board = new Board();
    pice: Pice = new Pice();

    constructor() {
        this.addKeyEvents();
    }

    addKeyEvents(): void {
        document.addEventListener("keydown", this.keyClick);
    }

    removeKeyEvents(): void {
        document.removeEventListener("keydown", this.keyClick);
    }

    keyClick(event: KeyboardEvent): void {
        console.log(this); // #document

        switch (event.keyCode) {

            // Left
            case 37:
                this.pice.move(-1, 0, this.board);
                break;
        }

    }

}
Dainel vdM
  • 253
  • 1
  • 2
  • 5
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Jared Smith Feb 18 '19 at 19:01
  • Side note, that OO design is....questionable. Having boards and pieces be a property of the player class I mean. – Jared Smith Feb 18 '19 at 19:02
  • [This](https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript) looks like a similar page just for typescript. – Stefan Becker Feb 18 '19 at 19:40

1 Answers1

0

You'll have to bind the function to the instance or use an arrow function to provide a proper context.

// Binding way.
class Player {
    constructor() {
        this.addKeyEvents();
        // Bind the function to `this` context.
        this.keyClick = this.keyClick.bind(this)
    }

    addKeyEvents(): void {
        document.addEventListener("keydown", this.keyClick);
    }

    keyClick(event: KeyboardEvent): void { /* ... */ }
}

// Arrow function way.
class Player {
    constructor() {
        this.addKeyEvents();
    }

    addKeyEvents(): void {
        // Create an intermediary arrow function that will keep the context.
        document.addEventListener("keydown", event => this.keyClick(event));
    }

    keyClick(event: KeyboardEvent): void { /* ... */ }
}
Mateusz Kocz
  • 4,492
  • 1
  • 25
  • 27
  • Both solutions succeeds in binding "this" to the keyClick method, but only the binding way works when also removing the event. – Dainel vdM Feb 18 '19 at 20:23