The difference between the. bind (),. Live (), and. Delegate () of jquery

Source: Internet
Author: User

Summary: The difference between jquery's. bind (),. Live (), and. Delegate () is not always obvious, however, if we have a clear understanding of all the differences, then this will help us to write more concise code, and prevent pop-up errors in the interactive app.

Basic elements

Dom Tree

First, it is helpful to visualize the DOM tree of a HMTL document. A simple HTML page looks like this:

Event bubbling (also known as event propagation)

When we click on a link, it triggers the Click event of the link element, which raises any execution of the function on the click event that we have bound to the element.

$ (' a '). bind (' click ', function () {alert ("that Tickles!")});

Therefore, a click action triggers the execution of the alert function.

The Click event is then propagated to the root of the tree, broadcast to the parent element, and then to each ancestor element, as long as the clicked event on one of its descendant elements is triggered, and the event is passed to it.

In the context of manipulating the DOM, document is the root node.

Now we can easily describe the differences between. bind (),. Live (), and. Delegate ().

. Bind ()

$ (' a '). bind (' click ', function () {alert ("that Tickles!")});

This is the simplest way to bind. jquery scans the document to find all the $ (' a ') elements and binds the alert function to each element's Click event.

. Live ()

$ (' a '). Live (' click ', function () {alert ("that Tickles!")});

jquery binds the alert function to the $ (document) element and uses ' click ' and ' a ' as arguments. Whenever an event bubbles onto the document node, it checks to see if the event is a click event, and whether the target element of the event matches the CSS selector of ' a ', and if so, executes the function.

The live method can also be bound to a specific element (or context) rather than document, like this:

$ (' A ', $ (' #container ') [0]). Live (...);

. Delegate ()

$ (' #container '). Delegate (' A ', ' click ', function () {alert ("that Tickles!")});

The jquery scan document looks for $ (' #container ') and binds the alert function to $ (' #container ') using the Click event and the CSS selector ' a ' as a parameter. Whenever an event bubbles to $ (' #container '), it checks to see if the event is a click event, and whether the target element of the event matches the CCS selector. If the results of both checks are true, it executes the function.

It can be noted that this process is similar to. Live (), but it binds handlers to specific elements rather than to the root of document. The savvy JS ' er may have made the conclusion that $ (' a '). Live () = = $ (document). Delegate (' A '), is that right? Well, no, not exactly.

Why. Delegate () is better than. Live ()

For several reasons, people are often more inclined to opt for the delegate method of jquery than the live method. Consider the following example:

$ (' a '). Live (' click ', function () {blah ()});
Or
$ (document). Delegate (' A ', ' click ', function () {blah ()});

Speed

The latter is actually faster than the former, because the former first has to scan the entire document to find all the $ (' a ') elements and save them as jquery objects. Although the live function only needs to pass ' a ' as a string argument for subsequent judgment, the $ () function does not know that the method being linked will be. Live ().

On the other hand, the delegate method only needs to find and store the $ (document) element.

One way to avoid this problem is to call live that is bound outside of (document). Ready () so that it executes immediately. In this way, it runs before the DOM gets populated, so it doesn't look for elements or create jquery objects.

Flexibility and chain capability

The live function is also quite confusing. Think of it as being chained to the set of $ (' a ') objects, but it actually works on the $ (document) object. For this reason, it can try to link the method to itself in a way that scares the dead. In fact, what I want to say is, with $.live (' a ',...) This form is a global jquery approach, and the live approach makes more sense.

Only CSS selectors are supported

Finally, there is a big drawback to the live approach, which is that it can only operate on a direct CSS selector, which makes it very inflexible.

For more information about the disadvantages of CSS selectors, see the Exploring JQuery. Live () and. Die () article.

Update: Thanks to Hacker news on Pedalpete and the Ellsass in the comments below remind me to join the next section.

Why Choose. Live () or. Delegate () instead of. Bind ()

After all, bind seems more explicit and straightforward, isn't it? Well, there are two reasons why we prefer to choose delegate or live instead of bind:

To attach handlers to DOM elements that might not yet exist in the DOM. Because bind is directly binding handlers to individual elements, it cannot bind handlers to elements that do not yet exist on the page.

If you run $ (' a '). Bind (...) and the new link is added to the page via Ajax, your bind handler is not valid for these newly added links. Live and delegate, on the other hand, are bound to another ancestor node, so it is valid for any element that is present or future within that ancestor element.

Or, to attach a handler to a single element or to a small group of elements, listen for events on the descendant elements instead of looping through and attaching the same function to each of the 100 elements in the DOM. Attaching a handler to a (or a small group) ancestor element rather than attaching the handler directly to all the elements on the page provides a performance benefit.

Stop spreading

The last reminder I want to do is related to event propagation. Typically, we can terminate the execution of a handler function by using an event method like this:

$ (' a '). bind (' click ', Function (e) {
E.preventdefault ();
Or
E.stoppropagation ();
});

However, when we use the live or delegate method, the handler is not actually running, and the function does not run until the event bubbles to the element that the handler is actually bound to. And so far, our other handler functions from. bind () have already run.

The difference between the. bind (),. Live (), and. Delegate () of jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.