Binding and unbinding event listeners is very simple with jQuery. But when you have multiple listeners bound to an event on an element, how do you unbind one of the listeners exactly? We need to understand the namespace of the event.
Look at the code below:
$('#element')
.on('click', doSomething)
.on('click', doSomethingElse);
Bind the event listener like above, When the element is clicked, both doSomething and doSomethingElse listeners are triggered. This is a convenience of using jQuery, you can add different listeners to the same event of an element at any time. Unlike with onclick, the new listener will overwrite the old one.
If you want to unbind one of the listeners, such as doSomething, how to do it?
Is that so?
$('#element').off('click ');
Attention! The above line of code will unbind all listeners for the element's click event, which is not the result we want.
Luckily jQuery’s .off() method can accept a second argument, just like .on() . As long as the name of the listener function is passed into the .off() method as the second parameter, the specified listener can be unbound.
$('#element').off('click ', doSomething);
But if you don’t know the name of this function, or you are using an anonymous function:
$('#element').on('click', function() {
console.log('doSomething');
});
How to accurately unbind a click event listener?
First enter the code:
$('#element ').on('click.myNamespace', function() {
console.log('doSomething');
});
This is not just about the click event as a parameter Pass in the .on() method, but specify a namespace for the click event, and then listen to the click event in this namespace. At this point, even if the listener is an anonymous function, it is actually "named". Now you can unbind the event listener from a specific namespace as follows.
$('#element').off('click .myNamespace');
This is another convenient and powerful function jQuery provides us, and its internal implementation is certainly interesting!