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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With