Skip to content
Advertisement

Can’t access the class variables from a event handler

I am making a web application for arranging seats, and I have written these codes:

class SeatMap {
    constructor (parentElement) {
        this.#createSeats();
    }

    #createSeats () {
        this.seatList = [];
        for (let a = 0; a < this.row; a++) {
            for (let b = 0; b < this.column; b++) {
                this.seatList[a].push(new Seat(this,a,b));
            }
        }
    }

class Seat {
    constructor(seatContainer, rowNum, colNum) {
        this.seatContainer = seatContainer;
        this.seatTB.addEventListener("keydown", this.#keydownTB);
    }

    // Key Events Handler
    #keydownTB (event) {
        const seatContainerConector = this.seatContainer;
        if (event.key === "ArrowRight") {
            console.log(seatContainerConector); // Undefined
        }
    }
}

// I only wrote codes related to the problem here.

However, console.log(seatContainerConector); just gives me back undefined.
I have tried to delete const seatContainerConector = this.seatContainer; and use console.log(this.seatContainer); instead, but it didn’t work.
How can I solve this?

Advertisement

Answer

Your code is hard to debug since you leave out some essential elements, like new SeatMap(), row and column, this.seatTB, etc.

One problem in your keydown event handler is that your scope is not what you expect. That causes this.seatContainer to refer to the wrong scope. Instead of the class instance you refer to the element that caused the keydown event. On that element, this.seatContainer is undefined

You can fix that with the arrow function.

this.seatTB.addEventListener("click",  (e) => this.keydownTB(e));

Now this will refer to the instance of new Seat() instead of the element that caused the event.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement