0

I'm trying to do the following:

  1. User left clicks and holds down the click, as a user moves their mouse (while holding down left click) the pointer move event will console.log "Pointer Move"
  2. On release of the left click (aka on pointerup event) I want to remove the pointer move event, therefore when a user moves their mouse it will no longer console.log "Pointer move"

I have something now in which my 'pointermove' event is always firing even after I trigger the pointer up event and remove it. You can see it in the log here - after pointer up I don't want it to fire pointer move anymore: enter image description here

Here's the code:

class Controls{
    constructor() {

        this.setControls();
        this.onPointerDown();
    }

    setControls() {
        window.addEventListener("pointerdown", this.onPointerDown);
    }

    onPointerDown(event) {
        window.addEventListener("pointermove", this.onPointerMove);
        window.addEventListener("pointerup", this.onPointerUp);
        console.log("Pointer Down");
    }

    onPointerMove(event) {
        console.log("Pointer Move");
    }

    onPointerUp(event) {
        console.log("Pointer Up");
        window.removeEventListener("pointermove", this.onPointerMove);
        window.removeEventListener("pointerup", this.onPointerUp);
    }
}

let controls = new Controls();
<div>Test</div>
Si Random
  • 103
  • 2
  • Your `this` context is sometimes wrong, so `this.onPointerMove` does not reference a function inside `onPointerDown` when invoked as a result of `window.addEventListener("pointerdown", this.onPointerDown);`. Fix that and it'll work as expected. – CertainPerformance Mar 13 '22 at 20:38
  • @CertainPerformance Thanks, I tried adding `.bind(this)` e.g. `this.onPointerUp.bind(this)` to all of them but it's still not working. – Si Random Mar 13 '22 at 20:42
  • 1
    Change all the method definitions from eg `onPointerMove(event) {` to `onPointerMove = (event) => {` – CertainPerformance Mar 13 '22 at 20:42

0 Answers0