jquery Event Binding methods The difference between bind, live, delegate, and on

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?

1. Preparation of knowledge

When we begin, some knowledge is necessary:

1). 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:



2). 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:

Copy the contents to the Clipboard program code $ (' 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.



3). Sample HTML

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

Copy content to Clipboard program code
1 <ulID= "Members"Data-role= "ListView"Data-filter= "true">2     <!--... more list items ... -3     <Li>4         <ahref= "detail.html?id=10">5             <H3>John Resig (author of jquery)</H3>6             <P><Strong>JQuery Core Lead</Strong></P>7             <P>Boston, states</P>8         </a>9     </Li>Ten     <!--... more list items ... - One </ul>


2.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:

Copy content to Clipboard program code
1 /*  23*/4 5   function    6 function (e) {});  


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 various browsers;
• Very convenient and simple to bind events to elements;
·. Click (),. Hover () ... These very convenient event bindings are a simple way to handle bind;
• For elements selected with ID, it is very good, 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 following live, delegate) implementation mode;

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

3.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:

Copy content to Clipboard program code
1 if(Delegatecount &&!) (Event.button && Event.type = = = = "click")) {2 3      for(cur = event.target; cur! = This; Cur = Cur.parentnode | | This) {4 5         //Don ' t process clicks (only) on disabled elements (#6911, #8165, #11382, #11764)6         if(Cur.disabled!==true|| Event.type!== "click") {7Selmatch = {};8Matches = [];9              for(i = 0; i < Delegatecount; i++) {TenHandleobj =Handlers[i]; OneSEL =Handleobj.selector; A  -                 if(Selmatch[sel] = = =undefined) { -Selmatch[sel] = Handleobj.needscontext? theJQuery (SEL, This). Index (cur) >= 0 : -Jquery.find (SEL, This,NULL, [cur]). length; -                 } -                 if(Selmatch[sel]) { + Matches.push (handleobj); -                 } +             } A             if(matches.length) { at Handlerqueue.push ({elem:cur, matches:matches}); -             } -         } -     } -}


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

Copy content to Clipboard program code
1 /*  23*/4 5   function    (e) {});


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 was not properly supported;
• When using event.stoppropagation () is useless, because all must reach document;
• 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 are performance problems when the elements of the event are deep in your DOM tree;

4.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.

Copy content to Clipboard program code
/* the. Delegate () method behaves in a similar fashion to the. Live ()    method, but instead of attaching the event Han Dler to the document, you    can choose where it is anchored ("#members"). The selector and    event information ("Li a" & "click") is attached    to the*/F Unction(e) {});

Advantages:
• You can choose to put the event on that element;
The chaining was properly supported;
jquery still needs to iterate over all of the selector/event data to determine the sub-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 on that event, although much less than the document, but you still have to waste time to find out;

5.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:

Copy content to Clipboard program code
1Bindfunction(types, data, fn) {2     return  This. On (types,NULL, data, FN);3 },4Unbindfunction(types, fn) {5     return  This. Off (types,NULL, FN);6 },7 8Livefunction(types, data, fn) {9JQuery ( This. Context). On (types, This. Selector, data, FN);Ten     return  This; One }, ADiefunction(types, fn) { -JQuery ( This. Context). Off (types, This. selector | | "**", FN); -     return  This; the }, -  -Delegatefunction(selector, types, data, fn) { -     return  This. On (types, selector, data, FN); + }, -Undelegate:function(selector, types, fn) { +     //(namespace) or (selector, types [, fn]) A     returnArguments.length = = = 1? This. Off (Selector, "* *"): This. Off (types, selector | | "**", FN); at},


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

Copy content to Clipboard program code
/*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 the events of a binding;
• Still offers the advantages of. Delegate (), of course, you can use it directly if you need to. bind ();

Disadvantages:
• may have some trouble with you because it hides the details of the three methods we introduced earlier;

6. 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;

Resources

[1].http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html
[2].http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

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.