Reputation: 15319
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.
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.
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?
Any help would be nice.
Upvotes: 4
Views: 860
Reputation: 33870
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 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;
$(window).on('resize', function1);
$(window).on('resize', function2);
//Only turn off event 2
$(window).off('resize', 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
!
Upvotes: 11
Reputation: 4824
Do something like this-
$(window).off('resize.myCustomEvent');
and vice versa to attach it
Upvotes: 1
Reputation: 36511
If you use named handlers (as opposed to anonymous functions) you can pass the name of the handler to off
to remove just that one (http://api.jquery.com/off/)
function flash() {
$( "div" ).show().fadeOut( "slow" );
}
$( "body" ).off( "click", "#theone", flash )
Upvotes: 1