The difference between BIND () and live.

Source: Internet
Author: User

There are three ways to bind events in jquery: Taking the click event as an Example

(1) target. Click (function (){});

(2) target. BIND ("click", function (){});

(3) target. Live ("click", function (){});

The first method is easy to understand. In fact, it is similar to the common JS usage, but it is just missing an on

The second and third methods both bind events, but the two are quite different. The following describes the differences, because jquery's framework is used in many ways, pay special attention to the differences between the two.

[Difference between bind and live]

The live method is actually a variant of the BIND method. Its basic functions are the same as those of the BIND method. They all bind an event to an element, however, the bind method can only bind events to existing elements. It is invalid for elements generated by using JS and other methods afterwards, while the live method just makes up for this defect of the BIND method, it can bind the generated elements to corresponding events. So how does the live Method Implement this feature? The following describes how it works.

The reason why the live method can bind the generated elements to the corresponding event is that"Event Delegate"Above, the so-called" event Delegate "means that events bound to the ancestor element can be used on its child element. The processing mechanism of the live method is to bind the event to the root node of the DOM tree, instead of directly binding the event to an element. Here is an example:

$ (". Clickme"). Live ("click", FN );

$ ("Body"). append ("<Div class = 'clickme'> steps for testing the live method </div> ");

When we click this new element, the following steps are taken in sequence:

(1) generate a click event and pass it to Div for processing.

(2) because no event is directly bound to the DIV, the event is directly bubbling to the DOM tree.

(3) events are continuously bubbling until the root node of the DOM tree binds the click event to the root node by default.

(4) execute the Click Event bound by live.

(5) check whether the Bound event object exists and determine whether to continue binding events. The event object is detected

Whether the matching element can be found in condition (event.tar get). Closest ('. clickme.

(6) through the (5) test, if the Bound event object exists, the bound event will be executed.

The live method checks whether the Bound event object exists only when an event occurs. Therefore, the live method can bind events to new elements or events. In contrast, the BIND determines whether the element of the binding event exists in the event binding phase, and only binds the current element instead of the parent node.

According to the above analysis, the benefits of live are really great. Why should we use the bind method? The reason why jquery should retain the bind method instead of using the live method to replace BIND is that live cannot completely replace bind in some cases.Major differencesAs follows:

(1) The bind method can bind any JavaScript event, while the live method only supports click, dblclick, keydown, keypress in jquery1.3,

Keyup,Mousedown, mousemove, mouseout, Mouseover, and mouseup. In jquery 1.4.1, the options include focus and blue.

Event (mapped to moreSuitable, and can be Bubble on focusin and focusout ). In addition, hover (ing) is also supported in jquery 1.4.1.

To "mouseenter mouseleave ").

(2) live () does not fully support elements found through DOM traversal. Instead, use. Live () directly after a selector ()

Method.

(3) When an element is bound to an event using the live method, if you want to prevent the event from being transmitted or bubbling, return false in the function.

UseStoppropagation () cannot prevent event transmission or bubbling.

 

 

 

 

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

 

 

 

Event bubbling (also known as event Propagation)
When we click a link, it triggers the Click Event of the link element. This event triggers the execution of any function on the click event that we have bound to this element.
CopyCodeThe Code is as follows:
$ ('A'). BIND ('click', function () {alert ('That tickles! ')})

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

The click event will then spread to the root direction of the tree, broadcast to the parent element, and then each ancestor element, as long as the click event on a child element of the tree is triggered, the event is passed to it.

In the context of Dom manipulation, document is the root node.
now we can easily explain the differences between. BIND (),. Live (), and. Delegate.
. BIND ()
copy the Code as follows: $ ('A'). BIND ('click', function () {alert ('That tickles! ') ;})
This is the simplest binding method. The jquery scan document finds all the $ ('A') elements and binds the alert function to the click event of each element.
. Live ()
copy the Code as follows: $ ('A'). Live ('click', function () {alert ('That tickles! ')})
jquery binds the alert function to the $ (document) element and uses 'click' and 'A' as parameters. Whenever an event bubbles to the document node, it checks whether the event is a click event and whether the target element of the event matches the 'A' CSS selector, if all are used, the function is executed.
the live method can also be bound to a specific element (or "context") instead of a document, as shown in the following code: $ ('A ', $ ('# iner') [0]). live ('click', function () {alert ('That tickles! ')})
. delegate ()
the copy code is as follows: $ ('# iner '). delegate ('A', 'click', function () {alert ('That tickles! ')})

Jquery scans the document for $ ('# iner') and binds the alert function to $ ('# iner') using the Click Event and the 'A' CSS selector as parameters. Whenever an event bubbles to $ ('# iner'), it checks whether the event is a click event and whether the target element of the event matches the CSS selector. If both checks are true, It executes the function.
It can be noted that this process is similar to. Live (), but it processesProgramBind to a specific element instead of a document. The Savvy JavaScript 'er may come to the conclusion that $ ('A '). live () ==$ (document ). delegate ('A'), is that true? Well, no, not exactly.
Why. Delegate () is better than. Live ()
For several reasons, people prefer to use jquery's delegate method instead of the live method. Consider the following example:
Copy the Code as follows: $ ('A'). Live ('click', function () {blah ()});
Or
$ (Document). Delegate ('A', 'click', function () {blah ()});
The latter is actually faster than the former, because the former first needs 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 parameter for subsequent judgment, the $ () function does not "know" that the method to be 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 bound outside of $ (document). Ready () so that it will be executed immediately. In this way, it runs before the DOM obtains the padding, so it does not search for elements or create jquery objects.

flexibility and chain capabilities
the live function is also confusing. Think about it, It is chained to the $ ('A') object set, but it actually works on the $ (document) object. For this reason, it can try to chain methods to itself in a way that is frightening. In fact, what I want to say is: $. Live ('A ',...) As a global jquery method, the live method is more meaningful.
only CSS selectors are supported.
the last point is that the live method can only operate on direct CSS selectors, this makes it very inflexible.
for more information about the shortcomings of the CSS selector, refer to the article listing ing jquery. Live () and. Die.
Update: Thanks to pedalpete on Hacker News and ellsass in the comments to remind me to join the next section.
Why choose. Live () or. Delegate () instead of. BIND ()
after all, the BIND seems more explicit and direct, isn't it? Well, there are two reasons we prefer to choose delegate or live instead of BIND:
1. to attach the handler to a DOM element that may not exist in the Dom. Because bind directly binds the handler to each element, it cannot bind the handler to an element that does not exist on the page.
2. If you run $ ('A'). BIND (...), After the new link is added to the page via Ajax, your bind handler is invalid for these newly added links. On the other hand, live and delegate are bound to another ancestor node. Therefore, live and delegate are valid for any element that exists within the ancestor element currently or in the future.
3. or, to attach the handler to a single element or a group of elements, listen to the events on the child element instead of looping and attach the same function to the 100 elements in the DOM one by one. Attaching a handler to one (or a group) ancestor element rather than directly attaching the handler to all elements on the page brings performance benefits.
stop propagation
the last reminder I want to make is related to event propagation. In general, we can terminate the execution of the processing function by using such an event Method:
copy the Code as follows:
$ ('A '). BIND ('click', function (e) {
E. preventdefault ()
E. stoppropagation () }< br>)

however, when we use the live or delegate method, the processing function is not actually running, the function runs only when the event bubbles to the elements actually bound to the handler. So far, our other processing functions from. BIND () have been running.

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.