Javascript 如何删除带有匿名函数的 addEventListener 的事件监听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5660131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:19:27  来源:igfitidea点击:

How to removeEventListener that is addEventListener with anonymous function?

javascriptevent-handlinganonymous-function

提问by Japboy

function doSomethingWith(param)
{
    document.body.addEventListener(
        'scroll',
        function()
        {
            document.write(param);
        },
        false
    ); // An event that I want to remove later
}
setTimeout(
    function()
    {
        document.body.removeEventListener('scroll', HANDLER ,false);
            // What HANDLER should I specify to remove the anonymous handler above?
    },
    3000
);
doSomethingWith('Test. ');

回答by Felix Kling

You can't. You have to use a named function or store the reference somehow.

你不能。您必须使用命名函数或以某种方式存储引用。

var handler;

function doSomethingWith(param) {
    handler = function(){
        document.write(param);
    };  
    document.body.addEventListener('scroll', handler,false);
}
setTimeout(function() {
     document.body.removeEventListener('scroll', handler ,false);
}, 3000);

The best would be to do this in a structured way, so that you can identify different handlers and remove them. In the example above, you obviously could only remove the last handler.

最好以结构化的方式执行此操作,以便您可以识别不同的处理程序并将其删除。在上面的示例中,您显然只能删除最后一个处理程序。

Update:

更新:

You could create your own handler handler (:)) :

您可以创建自己的处理程序处理程序 (:)):

var Handler = (function(){
    var i = 1,
        listeners = {};

    return {
        addListener: function(element, event, handler, capture) {
            element.addEventListener(event, handler, capture);
            listeners[i] = {element: element, 
                             event: event, 
                             handler: handler, 
                             capture: capture};
            return i++;
        },
        removeListener: function(id) {
            if(id in listeners) {
                var h = listeners[id];
                h.element.removeEventListener(h.event, h.handler, h.capture);
                delete listeners[id];
            }
        }
    };
}());

Then you can use it with:

然后你可以使用它:

function doSomethingWith(param) {
    return Handler.addListener(document.body, 'scroll', function() {
        document.write(param);
    }, false);
}

var handler = doSomethingWith('Test. ');

setTimeout(function() {
     Handler.removeListener(handler);
}, 3000);

DEMO

演示

回答by davin

You can't, you need a reference to the function:

你不能,你需要一个对函数的引用:

function doSomethingWith(param) {
   var fn = function(){ document.write(param); };
   document.body.addEventListener('scroll', fn, false);
   setTimeout(function(){ document.body.removeEventListener('scroll', fn, false); }, 3000);
}
doSomethingWith('Test. ');

回答by Simon Jentsch

You could also do this like that:

你也可以这样做:

const ownAddEventListener = (scope, type, handler, capture) => {
  scope.addEventListener(type, handler, capture);
  return () => {
    scope.removeEventListener(type, handler, capture);    
  }
}

Then you can remove the event listener like this:

然后你可以像这样删除事件监听器:

// Add event listener
const disposer = ownAddEventListener(document.body, 'scroll', () => { 
  // do something
}, false);

// Remove event listener
disposer();

回答by manoi

if you dont have to support IE, you can use the once option

如果您不必支持 IE,则可以使用一次选项

[Element].addEventListener('click', () => {...}, {
  capture: false,
  once: true
});