Jquery: remove eventhandler(e.g. 'cklick'), but keep other eventhandlers (for 'click')

58 Views Asked by At

if have a small jsfiddle example: https://jsfiddle.net/skmqjwt7/

I have multiple eventlisteners. All listening the same event (button.a click in the fiddle example). Now I want to disconnect one event listener, but I DON'T(!) want to disconnect all eventlisteners and reconnect those i want to keep.

I got multiple classes which got some event listeners and i want to disconnect just the eventlisteners of one class.

class a{
...stuff
   $('#main').on('bla', function(e){
     ...stuff
   });
}
class b{
...stuff
   $('#main').on('bla', function(e){
     ...stuff
   });
   function disconnectMe()
   {
      //disconnect B on('bla')
   }
}

class B doesnt know A (or any other classes which might listen to that event). So i just want to remove the eventlisteners of B, while keeping the eventlisteners of all other classes alive.

I cant handle thise disconnects globally like:

$('#main').off();
a.reconnect();
c.reconnect();

In my case class B is just getting data from backend and decides to stop listening to the event on its own.

Is this possible? In my current case, a custom event is triggered on $(document) and any other javascript class is able to listen, but i dont know how to remove just one listener.

1

There are 1 best solutions below

4
Razvan Bunga On

The unbind() Method is an inbuilt method in jQuery which is used to remove any selected event handlers. This method can be used to remove particular event handler, or stop specific functions. It works on any event handler using an event object.

Note: If no parameters are provided, the method works on all event handlers from the specified element. Syntax:

$(selector).unbind(event, function, eventObj)

Parameters: This method accepts three parameters as mentioned above and described below: event: It is an optional parameter which is used to specify events (one or more) to remove them from the elements. function: It is an optional parameter which is used to specify the name of the function to unbind from the specified event for the element. eventObj: It is an optional parameter which is used to specify the event object to remove from the event binding function.