kingPuppy
kingPuppy

Reputation: 3047

How to remove jQuery event listener from parent without removing similar listeners?

I am wondering if there is an elegant way to remove specific event listeners from a HTML element without affecting similar events.

Ex.

var a = {
  addEvent: function(){
     $('body').on('click', function(){
      //does something here.
     });
  }
}

var b = {
  addEvent: function(){
     $('body').on('click', function(){
      //does something else here.
     });
   }
}

a.addEvent();
b.addEvent();

So the question is: how do I remove object a's on click event without removing b's event?

$('body').off('click'); //removes both event listeners

I assume most ways will kill both listeners. It would be great to see any elegant responses.

Upvotes: 4

Views: 189

Answers (2)

kingPuppy
kingPuppy

Reputation: 3047

Great answer Josh (and I will give you the points).

The below does not work (I made a bad assumption to believe this would work)... striking through so no one uses this answer. Thanks @Guffa.

I found another solution to this issue worth sharing:

var x = $('body').on('click', function(){
                //does something here
        });

var y = $('body').on('click', function(){
                //does something else here
        });

x.off('click'); //this does not remove the event handler assigned to y

(I did not write the code inside the original objects for clarity)

Upvotes: 2

Josh Crozier
Josh Crozier

Reputation: 240928

One option would be to namespace the events:

var a = {
  addEvent: function(){
     $('body').on('click.a', function(){
       //does something here.
     });
  }
}

var b = {
  addEvent: function(){
     $('body').on('click.b', function(){
       //does something here.
     });
   }
}

a.addEvent();
b.addEvent();

$('body').off('click.a'); //removes the a event listener

Upvotes: 9

Related Questions