temp
temp

Reputation: 571

eventListener not removed on clicking

I'm trying to remove an eventListener when clicking on an Canvas element:

document.getElementById("canvas")
        .addEventListener("click", setPath, false);

function setPath() {
  if (check) {
    document.getElementById("canvas").
        addEventListener("mousemove", mouseOverPath, false);
  } else {
    document.getElementById("canvas").
        removeEventListener("mousemove", mouseOverPath, false);
  }

  function mouseOverPath(event) {
    drawLine.x = event.clientX;
    drawLine.y = event.clientY;
    drawLine.draw();
  }

}

document.getElementById("canvas").
        addEventListener("click", () => {
  if (check == true) {
    check = false;
  } else if (check == false) {
    check = true;
  }
}, false);
<canvas id="canvas" height="200" width="200" style="border:1px solid black;">

The if-statements are executed correctly but the removeEventListener isn't.

The check part:

Upvotes: 1

Views: 56

Answers (1)

t.niese
t.niese

Reputation: 40872

You problem is that you define mouseOverPath within setPath:

function setPath() {
  if (check) {
    document.getElementById("canvas").addEventListener("mousemove", mouseOverPath, false);
  } else {
    document.getElementById("canvas").removeEventListener("mousemove", mouseOverPath, false);
  }

  function mouseOverPath(event) {
    drawLine.x = event.clientX;
    drawLine.y = event.clientY;
    drawLine.draw();
  }

}

For every call of setPath the mouseOverPath is a different object, so the mouseOverPath for the addEventListener and the one for removeEventListener refer to different objects, and as of that removeEventListener does nothing.

You need to move the mouseOverPath function out if the setPath function.

Here a simplified test case of your problem:

var tmp;

function test() {
  if (!tmp) {
     // save the current foo for the first call of test
    tmp = foo
  } else {
    // the comparison of the current foo with tmp (the previous foo) is false
    console.log(tmp == foo)
  }

  function foo() {}
}

test()
test()

Upvotes: 5

Related Questions