问题
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. \');
回答1:
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
回答2:
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. ');
回答3:
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();
回答4:
if you dont have to support IE, you can use the once option
[Element].addEventListener('click', () => {...}, {
capture: false,
once: true
});
来源:https://stackoverflow.com/questions/5660131/how-to-removeeventlistener-that-is-addeventlistener-with-anonymous-function