如何使用带参数的函数添加和删除事件侦听器?
很抱歉,如果这是一个常见问题,但我无法通过搜索找到任何似乎相关的答案.
Sorry if this is a common question, but I couldn't find any answers that seemed pertinent through searching.
如果我像这样附加一个事件监听器:
If I attach an event listener like this:
window.addEventListener('scroll', function() { check_pos(box); }, false);
稍后尝试将其删除似乎不起作用,如下所示:
it doesn't seem to work to try to remove it later, like this:
window.removeEventListener('scroll', function() { check_pos(box); }, false);
我认为这是因为 addEventListener
和 removeEventListener
方法想要引用相同的函数,而我为它们提供了匿名函数,虽然它们在代码,实际上并不相同.
I assume this is because the addEventListener
and removeEventListener
methods want a reference to the same function, while I've provided them with anonymous functions, which, while identical in code, are not literally the same.
如何更改我的代码以使对 removeEventListener
的调用正常工作?box"参数指的是我在屏幕上跟踪的 <iframe>
的名称;也就是说,我希望能够为我拥有的每个 订阅一次
scroll
事件(数量不同),并且一旦 check_pos()
函数测量某个位置,它会调用另一个函数并移除事件监听器以释放系统资源.
How can I change my code to get the call to removeEventListener
to work? The "box" argument refers to the name of an <iframe>
that I'm tracking on the screen; that is, I want to be able to subscribe to the scroll
event once for each <iframe>
that I have (the quantity varies), and once the check_pos()
function measures a certain position, it will call another function and also remove the event listener to free up system resources.
我的预感是该解决方案将涉及闭包和/或命名匿名函数,但我不确定具体是什么样子,希望能举个具体的例子.
My hunch is that the solution will involve a closure and/or naming the anonymous function, but I'm not sure exactly what that looks like, and would appreciate a concrete example.
希望这是有道理的.
推荐答案
您是否尝试过维护对匿名函数的引用(如您建议的那样)?
Have you tried maintaining a reference to the anonymous function (like you suggested)?
所以:
var listener = function() {
check_pos(box);
};
window.addEventListener('scroll', listener, false);
...
window.removeEventListener('scroll', listener, false);
Mozilla 的文档建议同样的事情.
Mozilla's docs suggest the same thing.
相关文章