简体   繁体   English

单击时未删除eventListener

[英]eventListener not removed on clicking

I'm trying to remove an eventListener when clicking on an Canvas element: 我试图在单击Canvas元素时删除eventListener:

 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. if语句已正确执行,但removeEventListener未正确执行。

The check part: 检查部分:

You problem is that you define mouseOverPath within setPath : 您的问题是您在setPath定义mouseOverPath

 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. 对于setPath的每次调用, mouseOverPath是一个不同的对象,因此addEventListenermouseOverPathremoveEventListenermouseOverPath引用了不同的对象,而removeEventListener执行任何操作。

You need to move the mouseOverPath function out if the setPath function. 如果使用setPath函数,则需要将mouseOverPath函数移出。

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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM