Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery event namespace

Detailed explanation of jQuery event namespace

零下一度
零下一度Original
2017-06-17 15:36:05880browse

Using jquery Binding and unbinding Event listeners are very simple. 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 following code:

$(“#element”)
    .on(“click”, doSomething)
    .on(“click”, doSomethingElse);

Bind event listeners as above. When the element is clicked, both doSomething and doSomethingElse listeners will be triggered. This is a convenience of using jQuery, you can add different listeners to the same event of an element at any time. Unlike using 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.

Fortunately, jQuery’s .off() method can accept a second parameter, just like .on(). As long as the name of the listenerfunction 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 anonymous function:

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

How to accurately unbind a click What about event listeners? It’s time to learn about jQuery’s event namespace!

First the code:

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

Here is not just passing the click event as a parameter into the .on() method, but specifying a namespace for the click event and then monitoring the namespace click event inside. 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 that jQuery provides us, and its internal implementation is certainly interesting!

The above is the detailed content of Detailed explanation of jQuery event namespace. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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