Home > Web Front-end > JS Tutorial > A brief understanding of the namespace of jQuery events_jquery

A brief understanding of the namespace of jQuery events_jquery

WBOY
Release: 2016-05-16 17:12:57
Original
1102 people have browsed it

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:

Copy the code The code is as follows:

$('#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?
Copy code The code is as follows:

$('#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.
Copy code The code is as follows:

$('#element').off('click ', doSomething);

But if you don’t know the name of this function, or you are using an anonymous function:
Copy code The code is as follows:

$('#element').on('click', function() {
console.log('doSomething');
});

How to accurately unbind a click event listener?
First enter the code:
Copy the code The code is as follows:

$('#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.
Copy code The code is as follows:

$('#element').off('click .myNamespace');

This is another convenient and powerful function jQuery provides us, and its internal implementation is certainly interesting!
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template