添加带有sevral参数的事件侦听器,并在以后将其删除 [英] Add an event listener with sevral parameters and remove it later
问题描述
这似乎是一个非常受欢迎的问题,尽管我似乎没有找到任何答案.
This seems to be a very popular question though i didn't seem to find any pertinat answers.
我附加了一个事件监听器,例如:
I attach an event listen like :
window.addEventListener('scroll', fnName, false);
问题是fnName需要几个参数,所以我尝试了
The problem is that fnName expect several parameters, so i then triedl
window.addEventListener('scroll', (function( e ){
return fnName(e, some, param )
}()), false)
但随后window.removeEventListener
不再起作用,所以我尝试了:
but then window.removeEventListener
do not work anymore so i tried:
window.removeEventListener('scroll', (function( e ){
return fnName(e, some, param )
}()), false)
推荐答案
每次声明一个匿名函数时,它都会创建一个新的函数实例.如果要删除现有功能,则需要保留该功能实例的副本.
Every time you declare an anonymous function, it creates a new function instance. If you want to remove an existing function, you need to retain a copy of the function instance.
var temp = function () {
fnName(e, some, param);
};
window.addEventListener('scroll', temp, false);
//elsewhere,
window.removeEventListener('scroll', temp, false);
我还应该注意使用
I should also note that using
(function (e){
return fnName(e, some, param)
}());
以undefined
作为第一个参数立即调用fnName
.我怀疑那是你的意图.
calls fnName
immediately with undefined
as the first parameter. I doubt that's your intention.
这篇关于添加带有sevral参数的事件侦听器,并在以后将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!