Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
kingPuppy Avatar asked Dec 19 '22 05:12

kingPuppy


1 Answers

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
like image 135
Josh Crozier Avatar answered Dec 21 '22 18:12

Josh Crozier