zachThePerson
zachThePerson

Reputation: 704

Javascript "onmousemove" event not working with classes

I really don't know how to phrase this in the title, but I am trying to make a class that contains all event functions, but I am running into strange issues.

Here is some mock-up code of the problem.

class Mouse{
    constructor(){
        this.x = 0;
        this.y = 0;
    }
}

class MainClass{
    constructor(){
        this.mouse = new Mouse();
    }

    updateMouse(event){
        this.mouse.x = event.clientX;
        this.mouse.y = event.clientY;
    }
}

var mouse;
var main;

window.onload = function(){
    main = new MainClass();

    document.onmousemove = main.updateMouse;
}

The main problem I am having is that when I run it it returns the error "Cannot set property 'x' of undefined" which is strange, because when I step through the program main.mouse.x is defined, up until the document.onmousemove line.

If I move the updateMouse() function into the Mouse class, and do this instead:

mouse = new Mouse();
document.onmousemove = mouse.updateMouse();

then it works, however in the ACTUAL program I am trying to write, the updateMouse() method needs to call other methods in the MainClass, so I can't do this.

Upvotes: 0

Views: 433

Answers (1)

Azamantes
Azamantes

Reputation: 1461

You have to use

window.onload = function(){
    main = new MainClass();

    document.onmousemove = main.updateMouse.bind(main); // bound function
};

Try that. If you don't bind the function it will see 'this' as itself (document object).

Upvotes: 1

Related Questions