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?
2
Answers
Edit your
enable
function as follows: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 ofInteractionsManager
when the method is called.Regarding the OP’s comment targeting my above remark …
… a possible solution just needs to take burcu’s
bind
approach a little further …