最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

event listener - removing javascript eventlisteners - Stack Overflow

programmeradmin4浏览0评论

I have this following javascript to activate sometime

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

but I am having troubles removing the event listener when some i do this

document.removeEventListener('touchmove', function (e) { e.preventDefault(); }, false);

the function removeEventListener doesnt seem to work. I did a little search on similar cases and unfortunately i cant find the solution. I appreciate any help.

I have this following javascript to activate sometime

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

but I am having troubles removing the event listener when some i do this

document.removeEventListener('touchmove', function (e) { e.preventDefault(); }, false);

the function removeEventListener doesnt seem to work. I did a little search on similar cases and unfortunately i cant find the solution. I appreciate any help.

Share Improve this question asked Jan 30, 2012 at 9:13 Chinchan ZuChinchan Zu 9185 gold badges20 silver badges40 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

You are sending an anonymous function to the addEventListener call. Use a named function instead and send that to removeEventListener, like this:

function handleTouchMove(e) {
  e.preventDefault();
}
document.addEventListener('touchmove', handleTouchMove, false);

document.removeEventListener('touchmove', handleTouchMove);

Otherwise, the way you were doing it, the function you sent to removeEventListener was a pletely different function, even though it had the same contents.

You have to pass the actual same function reference like this:

function handleTouch(e) {
    e.preventDefault();
}

document.addEventListener('touchmove', handleTouch, false);

document.removeEventListener('touchmove', handleTouch, false);

You can't use a second copy of a different anonymous function even if they have the same code in them.

发布评论

评论列表(0)

  1. 暂无评论