A detailed description of the differences between bind () vs. live () vs. delegate () vs. on () in jquery

Source: Internet
Author: User

Reprinted from: http://zhuzhichao.com/2013/12/differences-between-jquery-bind-vs-live/

I've seen a lot of developers who are confused about the. bind (),. Live (),. Delegate (), and. On () and their differences in jquery.

If you have no patience or just want to see the summary, please jump to the end.

Before we dive into these methods, we'll get the HTML code ready.

[JavaScript]View PlainCopy 
    1. <pre>
    2. <ul id="members" data-role="ListView" Data-filter="true" ><!--... more list items ...- /c2>
    3. <li>
    4. <a href="detail.html?id=10" >
    5. <strong>jquery Core lead</strong>
    6. Boston, states
    7. </a></li>
    8. <!--... more list items ...--></ul>
    9. </pre>

. Bind ()

The. bind () registered event directly points to the corresponding DOM element. This method is available from jquery 1.0, and this approach is cool for handling cross-browser event binding issues. Yes, this method is convenient to use. The problem, however, is a variety of performance issues, as follows:

[JavaScript]View PlainCopy 
  1. Code Example:
  2. /* The. Bind () method attaches the event handler directly to the DOM
  3. element in question ("#members li a"). The. Click () method is
  4. Just a shorthand-to-write the. bind () method. */
  5. $ ( "#members li a"). Bind ( "click", function (e) {});
  6. $ ( "#members li a"). Click ( function (e) {});
Advantages
    • Cross-browser
    • Easily and quickly bind events
    • Simple implementation method (. Click (). Hover (), etc ... It's easy to use.
    • For a simple ID selector, using. bind () is not only convenient, but can respond instantly when the event is triggered.
Disadvantages
    • This method attaches the same handler to each matching element.
    • For dynamically added elements that belong to a match, the event will not be triggered.
    • Performance issues, when dealing with a large number of matching elements
    • If you want to handle adding events before the page loads, it will affect the load efficiency
. Live ()

The. Live () method uses the concept of event delegation to perform the so-called "magic Method". Calling the. Live () method looks just as convenient as calling the. bind () method. But the following implementation principles are different: the Live () method attaches an event handler to the root-level document to correlate the element and event information to. Allows event handlers to bind events and matching elements through bubbling by registering an event handler to the document (translator: Note that the event is actually on document). Once the event bubbles to the document, jquery determines whether the selector and event handlers have a match, and if so, invokes the corresponding event handler. Obviously there are performance issues in the process of user use, but it is very fast when the bindings are registered.

[JavaScript]View PlainCopy 
    1. Code Example:
    2. /* the. Live () method attaches the event handler to the root level
    3. Document along with the associated selector and event information
    4. ("#members li a" & "click") */
    5. $ ( "#members li a"). Live ( "click", function (e) {});


Advantages
    • As with the loop registration of. BIND () Multiple event handlers,. Live () registers only one event handler
    • The method of updating from. bind () to. Live () has few changes to the program and only needs to replace "bind" to "live"
    • A "magical" execution handler for dynamically added elements that belong to a match
    • It is possible to bind and trigger events almost without time before the document element is fully loaded
Disadvantages
    • This method has been abolished at the time of jQuery1.7, and you should gradually replace the method with your code.
    • Links are not able to support this method properly
    • This method is discarded because it can only bind the event handler to the document
    • Event.stoppropagation () is no longer valid because the event has been entrusted to the document.
    • Since all selectors and event information are attached to the document, a deterministic event is triggered and must be matched by a large amount of stored information to
    • Because events are delegated to the document, if the DOM is too deep, it can affect the performance
. Delegate ()

The behavior of the. Delegate () method is somewhat similar. Live (). But instead of attaching the selector and event information to the document, you can choose the DOM element that you want to attach, which allows the delegate of the event to work properly. If you skip the. Live () Introduction and analysis, please jump back to read, then I can express to you the following logic

[JavaScript]View PlainCopy  
    1. Code Example:
    2. /*.delegate () is handled similarly. Live (), but instead of attaching an event handler to the document, you can choose where it is ("#members"). The selector and event information ("Li a" and "click") will be appended to the #members element. */
    3. $ ( "#members"). Delegate (" li a", "click", function (e) {});

The. Delegate () method is very powerful. The above code attaches the event handler and the selector and event information to the #members. This, of course, is much more effective than. Live () attaching these content to the document. There are also many other year-round issues that have been passed. Delegate () This method solves the problem. See the detailed list of the following outlines.

Advantages
    • The location of additional selectors and event information can be freely selected
    • Links can also effectively support the
    • jquery still needs to iterate through the selector and event data to determine the match, but because it is able to select the location that the information is attached to, it is much smaller by the amount of the match.
    • Since this technique uses event delegates, it is well-handled to add dynamic processing to DOM elements
    • If you delegate the event to the document, you can also bind and invoke the document before it is all ready to be completed.
Disadvantages
    • method to change from. Bind () to. Delegate () More trouble
    • If you attach the selector and event data to the document, you still need a lot of matching information, but the storage is much smaller relative to. Live ().
. On ()

You know that the. bind (). Live and. Delegate () methods are all implemented through the same new Method –.on () (after jQuery1.7), the following snippet from jquery 1.7.1 codebase in GitHub ...

[JavaScript]View PlainCopy 
  1. Code Example:
  2. ... more code ...
  3. Bind: function (types, data, fn) {
  4. Return This.on (types, null, data, FN);
  5. },
  6. Unbind: function (types, fn) {
  7. Return This.off (types, null, FN);
  8. },
  9. Live: function (types, data, fn) {
  10. JQuery ( this.context). On (types, this.selector, data, FN);
  11. return this ;
  12. },
  13. Die: function (types, fn) {
  14. JQuery ( this.context). Off (types, this.selector | |  "* *", FN);
  15. return this ;
  16. },
  17. Delegate: function (selector, types, data, fn) {
  18. Return This.on (types, selector, data, FN);
  19. },
  20. Undelegate: function (selector, types, fn) {
  21. return arguments.length = = 1?
  22. This.off (Selector, "* *"):
  23. This.off (types, selector, FN);
  24. },
  25. ... more code ...
This means that the new method can be used as follows [JavaScript]View PlainCopy 
  1. Code Example:
  2. /* The jQuery. bind (),. Live (), and. Delegate () methods is just one
  3. Line pass throughs to the new JQuery 1.7. On () method */
  4. Bind
  5. $ ( "#members li a"). On ( "click", function (e) {});
  6. $ ( "#members li a"). Bind ( "click", function (e) {});
  7. Live
  8. $ (document). On ( "click", "#members li a", function (e) {});
  9. $ ( "#members li a"). Live ( "click", function (e) {});
  10. Delegate
  11. $ ( "#members"). On ( "click", "Li a", function (e) {});
  12. $ ( "#members"). Delegate (" li a", "click", function (e) {});


You'll notice, depending on how I call the. On () method to change its execution. You can consider the "overloaded". On () method to have different effects. This approach brings a lot of consistency to the API and hopefully reduces the confusion of those methods. Advantages
    • Unity for various event binding methods
    • Simplifies the jquery code base and removes redirects from a single interface because this method is called to implement. bind (). Live () and. Delegate ()
    • Still provides a handy. Delegate () method, but still provides support for the. bind () method.
Disadvantages
    • Because invoking the various forms of this method can lead to some confusion
Summarize

Don't worry if you're confused about the various types of event-binding methods, because legacy issues and APIs have been caused over time. Some people think of these methods as magical methods, but once you find out how they work it will be better for your project.

Points to keep in mind in this article:
    • Using the. Bind () method is a waste of resources because it matches each item in the selector and sets the same event handler one at a time
    • It is recommended to stop using the. Live () method because it has been deprecated because he has a lot of problems
    • The. Delegate () method "very good" is used to handle performance and response when adding elements dynamically
    • The new. On () method is primarily the ability to implement. bind (). Live () or even. Delegate ()
    • It is recommended to use the. On () method if your project uses 1.7+ jquery.

A detailed description of the differences between bind () vs. live () vs. delegate () vs. on () in 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.