我好像被困住了。
我有以下事件监听器:
window.addEventListener('scroll',scrollEventListener(scope,element,attrs,WallService,$state))
如果我这样做,即使没有滚动,它也会立即运行。
所以我把它包裹起来:
window.addEventListener('scroll',function(){scrollEventListener(scope,element,attrs,WallService,$state)})
但现在我无法引用它:
window.removeEventListener("scroll",scrollEventListener);
如何正确添加一个不会立即触发但我仍然可以引用的事件列表器,以便我可以删除监听器。
我正在使用 AngularJS 并且想要删除监听器,因为它应该只与指令一起存在,即它是这样的:
scope.$on("$destroy", function() {
window.removeEventListener("scroll",scrollEventListener);
});
最佳答案
因为你正在调用它。试试这个:
var scrollEvent = function(){scrollEventListener (<call with args>)};
或者
var scrollEvent = scrollEventListener.bind(this, <args separate by comma>)
然后
window.addEventListener('scroll',scrollEvent );
......
......
window.removeEventListener('scroll',scrollEvent );
就够了
关于javascript - EventListener 会立即触发,除非封装在匿名函数中,然后阻止 RemoveEventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123293/