Turn jQuery in Bind (), Live (), delegate (), on () difference

Source: Internet
Author: User

When we try to bind some events to the DOM element, I believe the above 4 methods are the most common. And what is the difference between them? What is the most effective way to use it?

Preparation of Knowledge:

When we begin, some knowledge is necessary:

Dom Tree

Just an example, this is a simulated DOM tree in the browser environment, which only plays the role of demo in the following code:

Event bubbling (aka event propagation) bubbles

Our page can be understood as a DOM tree, when we do something on the leaf node (such as the Click a element), if we do not artificially set stoppropagation (Moder Browser), cancelbubble (IE), Then all of its parent elements, ancestor elements will be affected, and the events they bind above will also have a role to play. Look at an example:

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

When we click on a, we first trigger the Click event that it itself binds to, and then it goes all the way up, triggering its parent element, all the binding click events on the ancestor element, as demonstrated.

Sample HTML

In order to demonstrate the following code, add some HTML code:

<ul id= "Members" data-role= "ListView" Data-filter= "true" >    <!--... more list items ...--    <li >        <a href= "detail.html?id=10" >            

Bind ():

. Bind () is the most straightforward binding method that binds the event type and handler function to the DOM element, which is the longest, and also solves the browser compatibility problem in event handling. But this method has some performance aspects, see the following code:

/* The. Bind () method attaches the event handler directly to    the DOM element in question ("#members li a"). The. Click () method is    

The above two lines of code complete the task is consistent, is to add the event handler to all the matching <a> elements. There are some efficiency problems here, on the one hand, we implicitly add the click handler to all the a tags, the process is expensive, and on the other hand it is a waste of execution, Because they all do the same thing and are executed again and again (for example we can hook it to their parent element, by bubbling can distinguish each of them, and then execute this event handler).

Advantages:

    • This approach provides a compatibility solution for event handling across a variety of browsers
    • Very handy for simple binding events to elements
    • . Click (),. Hover () ... These very handy event bindings are a simple way to handle bind
    • It is very good for the elements selected with the ID, not only to hook up quickly (because a page has only one ID), and when the event occurs, handler can be executed immediately (relative to the subsequent live, delegate) implementation

Disadvantages:

    • It binds events to all of the selected elements.
    • It is not bound to those elements that are added dynamically after it finishes executing
    • When there are many elements, there is an efficiency problem.
    • You can do bind () when the page is finished loading, so you may have an efficiency problem

. Live ()

The. Live () method uses the concept of event delegates to handle the binding of events. It is the same as binding an event with. bind (): The Live () method binds the corresponding event to the root element of the element you select, which is on the document element. Then all events bubbling up can be handled with the same handler. Its processing mechanism is this, once the event bubbles to the document, jquery will find selector/event metadata, and then decide that handler should be called. jquery 1.8.2 Source code:

View Code

When handler is executing, there are some delays due to bubbling participation, but the binding is particularly fast.

View Code

The good thing about code above is that we do not need to bind events on each element, but only one time on the document. Although this is not the quickest way, it is indeed the least wasted.

Advantages:

    • There is only one event binding here, binding to document instead of binding all elements like. bind ().
    • Those dynamically added Elemtns can still trigger events that were previously bound because the actual binding of the event is on the document
    • You can bind the required events before the document is ready.

Disadvantages:

    • It has not been recommended since 1.7, so you have to start phasing it out.
    • Chaining not being properly supported.
    • It is useless to use event.stoppropagation () because all the document is to be reached
    • Because all selector/event are bound to document, it is very slow when we use the Matchselector method to elect that event to be invoked.
    • There is a performance problem when the element of the event is deep in your DOM tree

. Delegate ()

. Delegate () a bit like. Live (), unlike. Live () is that it does not bind all of the event to document, but rather where you decide to put it. The same place as live () is the event delegation.

View Code

Advantages:

    • You can choose to put the event on that element.
    • Chaining's been properly supported.
    • jquery still needs to iterate over all the selector/event data to determine which child element to match, but because you can decide on that root element, you can effectively reduce the element you are looking for.
    • Can be used on dynamically added elements

Disadvantages:

    • You need to find that element that happened, though much less than document, but you still have to waste time to find it.

. On ()

In fact,. bind (),. Live (),. Delegate () are all implemented by. On (),. Unbind (),. Die (),. Undelegate (), and the same is done through. Off (), which is the source of the 1.8.2:

View Code

Let's see how we can use. On () to overwrite events previously registered with. Bind (),. Live (),. Delegate ():

/* The jQuery. bind (),. Live (), and. Delegate () methods is just one line    pass throughs to the new jquery 1.8.2. On () Method *///bind$ ("#members li a"). On ("click", Function (e) {}); $ ("#members li a"). Bind ("click", Function (e) {}); live$ (document). On ("click", "#members li a", function (e) {});  $ ("#members li a"). Live ("Click", Function (e) {});//delegate$ ("#members"). On ("Click", "Li a", function (e) {}); $ ("#members"). Delegate ("Li a", "click", Function (e) {});

Advantages:

    • Provides a way to unify bound events
    • Still offers the advantages of. Delegate (), of course, you can use it directly if needed. Bind ()

Disadvantages:

    • May be a bit of a problem for you, because it hides the details of the three methods we introduced earlier.

Conclusion:

    • The cost of using. bind () is very large, and it hooks the same event handler to all matching DOM elements
    • Do not use. Live (), it is no longer recommended, and there are many problems
    • . Delegate () provides a good way to improve efficiency, and we can add an event handling method to dynamically added elements.
    • We can use. On () to replace the above 3 methods

Turn jQuery in Bind (), Live (), delegate (), on () difference

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.