javascripttypescriptvite

javascript can't access private field or method error on event


I get the following error when I click:

Uncaught TypeError: can't access private field or method: object is not the right class
    #clickEventHandler index.js:67
    enable index.js:45

I don't get any errors in my IDE and I don't understand what might be wrong.

Relevant code:

InteractionsManager

class InteractionsManager {
    #putHandler
    #eventListener

    constructor(putCallback) {
        this.#putHandler = new PutHandler(putCallback)
        this.#eventListener = null
    }

    /**
     * starts listening to "click" event
     */
    enable() {
line 45:        this.#eventListener = document.body.addEventListener("click", this.#clickEventHandler)
    }

    /**
     * 
     * @param {MouseEvent} e 
     */
    #clickEventHandler(e) {
        const mousePos = getMousePos(e);

line 67:        this.#putHandler.putTHandler(mousePos)
    }
}

PutHandler

class PutHandler {
    putTHandler(mousePos) {
        
    }
}

Any idea what might be wrong?


Solution

  • Edit your enable function as follows:

    enable() {
        this.#eventListener = document.body.addEventListener("click", this.#clickEventHandler.bind(this))
    }
    

    When you pass a method reference like this.#clickEventHandler directly, the event listener does not know about the class instance that it belongs to, causing this inside #clickEventHandler to point to the event target (document.body in this case). By binding this explicitly (with .bind()), you ensure that this still refers to the instance of InteractionsManager when the method is called.