In Jquery, the differences between. bind (),. live (),. delegate () and. on () are described in detail. jquery. bind

Source: Internet
Author: User

In Jquery, the differences between. bind (),. live (),. delegate () and. on () are described in detail. jquery. bind

Introduction

Recently, many web developers have many questions about the. bind (). live (). delegate () and. on () methods in jquery. These questions are usually about the real differences between them and when to use them. The following article will introduce the differences between the four methods in detail. Each method is described in detail. If not, let's take a look at the detailed introduction:

Before learning about these methods, let's take a look at common HTML as a sample for writing jquery sample methods.

<Ul id = "members" data-role = "listview" data-filter = "true"> <! --... Other li... --> <li> <a href = "detail.html? Id = 10 "rel =" external nofollow "> 

Bind Method

.bind()The method registers the event type and an event handler function directly to the selected DOM element. This method has been used for the longest time. During this period, it solves various cross-browser problems. When you use it to connect to the event processing function, it is still very simple, but there are also some performance problems, which will be listed below.

/*. Bind () method registers the event type and an event handler function directly to the selected DOM element. The. click () method is short for the. bind () method. */$ ("# Members li "). bind ("click", function (e) {}); $ ("# members li "). click (function (e ){});

.bind()The method will connect the event handler to all matched a tags. This method is not good. In doing so, it not only implicitly iterates and attaches event processing functions to all matching elements, but also these operations are very wasteful (redundant ), because these same event handlers are repeatedly added to all matching tags.

Advantages:

  • Applicable to various browsers
  • The connection event processing function is very convenient and convenient.
  • Available .click(),.hover()And other short-form methods to more easily connect to event processing functions
  • For a simple ID selector, use.bind() The method not only quickly connects to the event handler function, but also calls the event handler function almost immediately when the event is triggered.

Disadvantages:

  • In this way, all event handlers are appended to all matching elements.
  • Cannot dynamically match elements with the same Selector
  • Performance problems occur when a large number of matching elements are operated.
  • Additional operations are completed in the early stage, which may cause performance problems during page loading.

Use the Live Method

.live()The method uses the concept of event delegation to implement the so-called "magic ". You calllive()The method is like callingbind()The method is as convenient. However, on this surface,.live()The method is significantly different from the former. .live()Method: attach the selector and event information associated with the event processing function to the root-level element (document) of the document ). By registering event information on the document, this event handler function allows all events that bubble to the document to call it (such as delegate and propagation events ). Once an event bubbles to the document element, Jquery determines which event processing function should be called Based on the selector or Event metadata, if this event processing function exists. This extra work will have a certain impact on the performance of user interaction, but the process of initializing registration events is quite fast.

/* The method attaches the selector and event information associated with the event processing function to the root-level element (that is, document) of the document ("# members li a" & "click ") */$ ("# members li "). live ("click", function (e ){});

Compared with the preceding bind () method, the. bind () method has the advantage that it only attaches the event processing function to the document element once rather than many times. This will not only speed up, but also reduce the waste of performance. However, using this method will also cause many problems, which will be listed below.

Advantages:

  • All event processing functions are registered only once, insteadbind()Perform multiple registration in that way
  • Setbind()Update methodlive()The method is very convenient. You only need to replace "bind" with "live ".
  • Those elements dynamically added to the DOM will also be magically matched, because the real event information is registered to the document element.
  • You can connect to the event processing function before the file is loaded, which helps you make better use of the time you may not use.

Disadvantages:

  • This method has been abandoned in Versions later than Jquery 1.7. You should gradually discard it in your code.
  • The chain operation is not supported correctly when this method is used, and some errors may occur.
  • Basically, the matching operation is useless because it is only used to register the event processing function on the document element.
  • Useevent.stopPropogation() The method will be useless, because the event has always been delegated to the document element.
  • Because all selector or event information is attached to the document element, once an event is called, jquery uses the matchesSelector method in a large amount of stored metadata to determine which event handler function will be called, if any.
  • Because the events you connect are always delegated to the document. If your DOM level is deep, this will lead to certain performance problems.

Use the Delegate Method

.delegate()Method andlive()The implementation method is similar. Instead of attaching selector or event information to document, you can specify additional elements. Like the live () method, this method uses event Delegate to work correctly.

If you skip.live() Method Introduction, you may have to go back and look at it again, because it involves some of the internal logic I have previously stated.

/*. The delegate () method attaches the selector and event information ("li a" & "click") to your specified Element ("# members "). */$ ("# Members"). delegate ("li a", "click", function (e ){});

.delegate()The method is very powerful. In the above example, the selector and event information associated with the event processing function will be appended to the (# members ") element. Uselive()This is much more efficient becauselive()The method always attaches the selector and event information associated with the event processing function to the document element. In addition.delegate()Methods To solve many other problems. See the details listed below.

Advantages:

  • You can choose to append the selector or event information to the specified element.
  • The matching operation is not executed before, but is used to register the specified element.
  • Chain operations can be correctly supported
  • Jquery still needs to iterate the selector or event information to match the element. However, because you can select which element as the root element, the amount of filtering will be greatly reduced.
  • Because this technology uses the event Delegate mechanism, it can match the elements dynamically added to the DOM.
  • You can connect to the event handler before the document is loaded.

Disadvantages:

  • Slave.bind()The method cannot be upgraded directly.delegate()Method
  • Jquery still needs to use the marchesSelector method to filter the selector or event information appended to the specified root element to determine which event handler function will be called. However, the metadata appended to the specified root element is betterlive()Method is much smaller.
  • Performance problems occur when a large number of matching elements are operated.
  • Additional operations are completed in the early stage, which may cause performance problems during page loading.

Use the On Method

You know, in Jquery 1.7.bind() ,.live() And.delegate()You only need to use.on()You can call them in one way. Of course.unbind(), .die() And.undelegate()The same is true. The code snippet is extracted from the source code of Jquery 1.7.

bind: function( types, data, fn ) { return this.on( types, null, data, fn );},unbind: function( types, fn ) { return this.off( types, null, fn );},live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this;},die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this;},delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn );},undelegate: function( selector, types, fn ) { return arguments.length == 1 ?   this.off( selector, "**" ) :   this.off( types, selector, fn );}

With this in mind, use.on()The method looks like the following method...

/* Jquery's. bind (),. live () and. the delegate () method only needs to use '. on () 'method one way to call them * // Bind $ ("# members li "). on ("click", function (e) {}); $ ("# members li "). bind ("click", function (e) {}); // Live $ (document ). on ("click", "# members li a", function (e) {}); $ ("# members li "). live ("click", function (e) {}); // Delegate $ ("# members "). on ("click", "li a", function (e) {}); $ ("# members "). delegate ("li a", "click", function (e ){});

You may have noticed how to use.on()The method determines how it calls other methods. You can think.on()Methods are "reloaded" by methods with different signatures, and these methods implement different event binding connection methods..on()The emergence of Methods brings consistency in many aspects to the API, and hopes to make things less confusing.

Advantages:

  • Make the binding methods of various events consistent.
  • Because in Jquery source code.bind(),.live() And.delegate()The method actually calls this method, which simplifies the jQuery code base and deletes the first-level redirection.
  • This method is still available.delegate()And provides.bind()Method support, if needed.

Disadvantages:

  • There are some questions, because the actual execution method of the method will change according to how you call the method.

Summary

If you are confused about different binding event methods, don't worry, because the API has been developing for a while and there are a lot of previous experiences to learn from. There are also many people who regard these methods as magic, but once you understand the principles behind their work, it will help you understand how to better deal with projects.
The following is the essence of this article...

  • Use.bind()The method is a waste of performance because it attaches the same event handler to every matching element.
  • You should stop using.live()This method causes many problems when it is discarded.
  • Use.delegate()The method will bring you many benefits when you need to solve some performance problems and handle dynamically added elements
  • New.on()The method is to simulate.bind(),.live() And.delegate()The implemented syntactic sugar depends on how you call it.
  • The new direction is to use the new.on()Method. Familiarize yourself with the syntax and start using it in all your Jquery 1.7 and later projects!

Do you have any new supplements to the advantages or disadvantages listed above? You have recently started usingdelegate()Method? You.on()How can this problem be solved? Let me write your thoughts into comments! Thank you!

For the first translation, there may be some inaccessibility in the article. I hope you can understand it. After all, I am still a student!

Well, that's probably the case. The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Original article link

Related Article

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.