ES6中移除事件监听器

3

I have following code:

document.getElementsByClassName('drag')[i].addEventListener('mousedown', (e) => {
    console.log('mousedown' + i);
});

如果我能在监听器内部命名函数,那么这将会很容易。但在我的情况下不可能。

代码应该是这样的:

e.currentTarget.removeEventListener(e.type, nameFunction);

有没有办法让它工作?谢谢。

2
你难道无法将该函数的引用单独存储?! let cb = (e) => { ... }; ...addEventListener(..., cb); removeEventListener(..., cb);? - deceze
2
为什么你不能给函数命名? - itamar
1
@deceze 期待您的完整回复。 - radek2s
@itamar 是箭头函数,所以保存它的引用到一个变量中也很容易,就像 deceze 在上面展示的那样。 - nem035
3个回答

2
有两种方式。
  1. When you define a function, then add and remove the listener when you want:

    // Define a function
    const handler = () => {
        console.log('Click event...');
    }
    
    // Select the element and add event listener
    const img = document.querySelector('img');
        img.addEventListener('click', handler, false);
    
    // ...
    
    // Remove the event listener
    img.removeEventListener('click', handler, false);
    
  2. When you add an event listener and remove it on event:

    // Select the element and add event listener
    const img = document.querySelector('img');
       img.addEventListener('click', function handler(event) {
          console.log('Click event...');
    
          // On event, remove the event listener
          event.currentTarget.removeEventListener(event.type, handler);
       });
    

2

是的,你可以这样写。

(注:该文本已经是中文,无需翻译)
document.getElementsByClassName('drag')[i].addEventListener('mousedown', mouseDownFun);
function mouseDownFun(e){
  console.log('mousedown' + i);
}
e.currentTarget.removeEventListener(e.type, mouseDownFun);

所以每当鼠标按下事件被触发时,它将在mouseDownFun中监听。

1

如果我能在监听器内部命名函数,那么这将变得很容易。但在我的情况下不可能。

如果箭头函数无法满足您的需求,请不要使用它。

document.getElementsByClassName('drag')[i].addEventListener('mousedown', function handler(e) {
    console.log('mousedown' + i);
    e.currentTarget.removeEventListener(e.type, handler);
});

他能否为箭头函数命名,并以这种方式使用名称? - prosti
只有将其分配给一个变量才能实现。 - Felix Kling
2
@prosti的“fat”表达方式暗示了箭头函数有多种类型,但实际上只有一种;只需说“箭头函数”即可。 - Mulan
@naomik,39岁的未来时代脚本小子可能很快会将这样的 "->" 带入ES世界,到那时我的评论就不再准确了。 - prosti
@prosti,这很有趣,但我认为现在最好称其为实际名称。如果将来出现新的语法,我相信它会有自己的名称。 - Mulan
@naomik,是的,我想我第一次听到“fat arrow”这个术语是在Dan Abramov在Egghead上免费课程中,但从现在开始我会遵循你的提示。 - prosti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接