Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript (jquery) - Multiple Handlers attached to one event: How to detach only one?

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.

like image 729
darksoulsong Avatar asked Dec 12 '22 05:12

darksoulsong


2 Answers

Here 2 different suggestions. You can either give a namespace to your event or pass a none anonymous function when binding.

Example when using namespace :

$(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;

Example using named functions :

$(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!

like image 109
Karl-André Gagnon Avatar answered Feb 12 '23 12:02

Karl-André Gagnon


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 )
like image 34
Rob M. Avatar answered Feb 12 '23 10:02

Rob M.