使用removeEventListener删除包装函数回调

时间:2013-06-21 15:34:36

标签: javascript callback event-listener

我有这个代码,在点击和拖动时在画布上拖动一个球。

canvas.addEventListener('mousedown', function () {
  var initialClickX = mouse.x;
  var initialClickY = mouse.y;
  var initialBallX = ball.x;
  var initialBallY = ball.y;

  canvas.addEventListener('mousemove', function() {
      onMouseMove(initialClickX, initialClickY, mouse.x, mouse.y, initialBallX, initialBallY)
  }, false);

}, false);

function onMouseMove(initialClickX, initialClickY, mouseX, mouseY, initialBallX,     initialBallY){
    ball.x = mouseX + initialBallX - initialClickX;
    ball.y = mouseY + initialBallY - initialClickY;
    draw();
}

麻烦的是,当我用鼠标按钮时,我无法让球停止拖动。我知道我需要添加:

    canvas.removeEventListener('mousemove', function() {
      onMouseMove(initialClickX, initialClickY, mouse.x, mouse.y, initialBallX, initialBallY)
  }, false);

但是因为函数在包装器中,所以上面没有效果,并且球仍然粘在我的光标上。任何人都可以建议解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

不要使用匿名功能。您需要保留对事件侦听器函数的引用,以便以后删除。

canvas.addEventListener('mousedown', function () {
  var initialClickX = mouse.x;
  var initialClickY = mouse.y;
  var initialBallX = ball.x;
  var initialBallY = ball.y;

  function wrapper() {
      onMouseMove(initialClickX, initialClickY, mouse.x, mouse.y, initialBallX, initialBallY)
  }

  canvas.addEventListener('mousemove', wrapper, false);

  // some time later
  canvas.removeEventListener('mousemove', wrapper);

}, false);