Javascript(jquery) - 附加到一个事件的多个处理程序:如何只分离一个事件? [英] Javascript (jquery) - Multiple Handlers attached to one event: How to detach only one?
问题描述
在这个模块中我正在研究我在窗口中有一个'resize'事件的监听器。每次运行模块时,我都需要检查是否已经有一个监听器注册到该事件并将其分离,以避免不必要的行为,内存泄漏等。
In this module I'm working on I have a listener to a 'resize' event in the window. Every time the module is ran, I need to check if there's already a listener registered to that event and detach it, in order to avoid unwanted behavior, memory leaks and etc.
到目前为止一切顺利,但是,在我们正在开发的这个应用程序中,有些处理程序已经附加到'resize'事件,我无法调用 $(window).off(' resize')
,因为这会刷新之前由其他插件或模块注册的所有其他事件处理程序。
So far so good, but, in this application we are working on, chances are that some handlers are already attached to the 'resize' event and I can't call $(window).off('resize')
, as this would flush all the other event handlers previously registered by other plugins or modules.
正如那样说,我想知道是否有办法识别我的处理程序,只分离我自己注册的东西。如何在我的事件处理程序中设置标识符,以便在 .off()
函数中引用?
Being that said, I would like to know if there's a way to identify my handler and only detach things that I have registered myself. How do I set an identifier to my event handler in order to be referenced in the .off()
function?
任何帮助都会很好。
推荐答案
这里有两个不同的建议。您可以为事件指定命名空间,也可以在绑定时传递无匿名函数。
Here 2 different suggestions. You can either give a namespace to your event or pass a none anonymous function when binding.
$(window).on('resize.event1', function(){});
$(window).on('resize.event2', function(){});
//Only turn off event 2
$(window).off('resize.event2');
jQuery允许您识别您的活动。此行为称为命名空间。当前事件和事件名称必须用点分隔。在这种情况下,我绑定2调整大小事件(点的左侧),一个名称 event1
,另一个与 event2
。
jQuery allow you to identify your event. This behaviour is called namespace. The current event and the event name must be separate by a dot. In that case, i am binding 2 resize event (left side of the dot), one with the name event1
and the other with event2
.
通过识别事件,您可以在对象具有多个相同事件时删除(或触发)单个事件。
By identifying the event, you can remove (or trigger) single event when an object have multiple of the same event.
$(window).trigger('resize'); //Trigger both;
$(window).trigger('resize.event2'); //Trigger event2;
使用命名函数的示例:
Example using named functions :
$(window).on('resize', function1);
$(window).on('resize', function2);
//Only turn off event 2
$(window).off('resize', function2);
如果传递的函数与当前事件函数匹配,则关联无匿名函数可以删除事件。因为 function2 === function2
,只有第二个函数将被删除,因为 function1!== function2
!
Associating a none anonymous function allow you to remove the event if the passed function match the current event function. Because function2 === function2
, only the second function will be remove since function1 !== function2
!
这篇关于Javascript(jquery) - 附加到一个事件的多个处理程序:如何只分离一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!