The namespace of jQuery events is simple to understand

  • 2020-03-29 23:58:35
  • OfStack

Unbinding event listeners with jQuery bindings is very simple. But when you bind multiple listeners to an event for an element, how exactly do you unbind one of them? We need to understand the namespace of the event.

Look at this code:
 
$('#element') 
.on('click', doSomething) 
.on('click', doSomethingElse); 

Bind event listeners like above, and when an element is clicked, both the doSomething and doSomethingElse listeners are fired. This is a convenience of using jQuery, where you can add different listeners to the same event of an element at any time. Unlike with onclick, the new listener overwrites the old.

So if you want to unbind one of these listeners, say doSomething, what do you do?

Is that right?
 
$('#element').off('click'); 

Attention! The above line of code unbinds all listeners of the element's click event, which is not what we want.

Fortunately, jQuery's.off () method takes a second argument, just like.on (). Simply pass the name of the listener function as the second argument to the.off() method to unbind the specified listener.
 
$('#element').off('click', doSomething); 

But if you don't know the name of the function, or if you're using an anonymous function:
 
$('#element').on('click', function() { 
console.log('doSomething'); 
}); 

How exactly can you unbind a click event listener?
Code first:
 
$('#element').on('click.myNamespace', function() { 
console.log('doSomething'); 
}); 

Instead of just passing the click event as an argument to the.on() method, you specify a namespace for the click event and then listen for the click events in that namespace. At this point, even if the listener is an anonymous function, it is actually named. Now you can unbind the event listener in a specific namespace as follows.
 
$('#element').off('click.myNamespace'); 

This is another handy and powerful feature jQuery has to offer, and its internal implementation must be interesting!

Related articles: