pileup
pileup

Reputation: 3262

method not defined when calling from inside an event listener

I have a Game class with canvas and I add an event listener for mouse clicks in the constructor.

I have a method that should log the position of the mouse click, but I get error that this method is not defined:

class Game {

    constructor(canvas, event) {
        this.canvas = canvas;                        
        this.canvas.addEventListener('mousedown', function (e) {
            getClickPosition(canvas, e)
        })
    }

    getClickPosition(canvas, e) {
        const rect = canvas.getBoundingClientRect()
        const x = event.clientX - rect.left
        const y = event.clientY - rect.top
        console.log("x: " + x + " y: " + y)
    }
    }
const canvas = document.querySelector('canvas')
const game = new Game(canvas)

Upvotes: 0

Views: 511

Answers (1)

Andy
Andy

Reputation: 63524

Use an arrow function expression (to preserve this) and call this.getClickPosition():

this.canvas.addEventListener('mousedown', (e) => {
  this.getClickPosition(canvas, e);
});

Upvotes: 3

Related Questions