JQuery event binding and delegation, jquery event binding

Source: Internet
Author: User

JQuery event binding and delegation, jquery event binding

Binding and delegation of jQuery eventsIt can be implemented in multiple ways: on (), bind (), live (), delegate (), and one ().

 

Sometimes we may bind an event as follows:

Js Code  
  1. $ ("# Div1"). click (function (){
  2. Alert ("triggered after clicking ");
  3. });

 

The above event binding can be implemented in multiple ways:

 

1. on ()

Js Code  
  1. // No data Parameter
  2. $ ("P"). on ("click", function (){
  3. Alert ($ (this). text ());
  4. });
  5. // There are data Parameters
  6. Function myHandler (event ){
  7. Alert (event. data. foo );
  8. }
  9. $ ("P"). on ("click", {foo: "bar"}, myHandler)

 

What corresponds to on () isOff ()To remove event binding:

Php code  
  1. Var foo = function (){
  2. // Code to handle some kind of event
  3. };
  4. //... Now foo will be called when paragraphs are clicked...
  5. $ ("Body"). on ("click", "p", foo );
  6. //... Foo will no longer be called.
  7. $ ("Body"). off ("click", "p", foo );

 

Off (): Remove the binding on ().

One (): Bind only once.

 

2. bind ()

Parameters:

(Type, [data], function (eventObject ))

Type:Contains one or more event types. Multiple events are separated by spaces. For example, "click" or "submit" can also be a Custom Event name.

Data:Extra data object passed to the event object as the event. data Attribute Value

 

Fn:The processing function bound to the event of each Matching Element

 

(Type, [data], false)

Type:Contains one or more event types. Multiple events are separated by spaces. For example, "click" or "submit" can also be a Custom Event name.

Data:Extra data object passed to the event object as the event. data Attribute Value

 

False:Setting the third parameter to false will invalidate the default action.

 

Bind multiple event types at the same time:

Js Code  
  1. $ ('# Foo'). bind ('mouseenter mouseleave', function (){
  2. $ (This). toggleClass ('entered ');
  3. });

 

Bind multiple event types/handlers at the same time:

Js Code  
  1. $ ("Button"). bind ({
  2. Click: function () {$ ("p"). slideToggle ();},
  3. Mouseover: function () {$ ("body" ).css ("background-color", "red ");},
  4. Mouseout: function () {$ ("body" ).css ("background-color", "# FFFFFF ");}
  5. });

 

You can transmit some additional data before the event processing.

Js Code  
  1. Function handler (event ){
  2. Alert (event. data. foo );
  3. }
  4. $ ("P"). bind ("click", {foo: "bar"}, handler)

 

 

False is returned to cancel the default action and prevent event bubbles.

Js Code  
  1. $ ("Form"). bind ("submit", function () {return false ;})

 

Bind Problems

If the table contains 10 columns and 500 rows for which you want to bind a click event, searching for and traversing 5000 cells will significantly slow down script execution, the storage of 5000 td elements and corresponding Event Handlers also occupy a large amount of memory (similar to letting everyone stand at the door and wait for the express delivery ).

 

Based on the previous example, if we want to implement a simple photo album application, each page will display only 50 thumbnail photos (50 cells ), you can click the "page x" (or "next page") link to dynamically load 50 more photos from the server using Ajax. In this case, it seems that the. bind () method is acceptable for binding events to 50 cells.

 

This is not true. By using the. bind () method, only 50 cells on the first page are bound with a click event. This click event is not found in the subsequent cells on the Dynamically Loaded page. In other words,. bind () can only bind events to existing elements when calling it, and cannot bind events to new elements in the future (similar to new employees cannot receive express deliveries ).

 

Event delegation can solve the above two problems. Specifically, you only need to replace the. bind () method with the. live () method added by jQuery 1.3:

Js Code  
  1. $ ("# Info_table td"). live ("click", function () {/* show more information */});

Here. the live () method binds the click event to the $ (document) object, which is not reflected in the Code. the live () method is criticized for an important reason, which will be discussed in detail later), and you only need to bind $ (document) Once (not 50 times, not 5000 times ), then, you can process the click events of the subsequently Dynamically Loaded photo cells. When receiving any event, the $ (document) object checks the event type and event Target. If it is a click event and the event target is td, it executes the handler entrusted to it.

 

Unbind (): Remove bind binding.

 

3. live ()

So far, everything seems perfect. Unfortunately, this is not the case. Because the. live () method is not perfect, it has the following main disadvantages:

  • Compile get or its ancestor element for comparison, so generating this jQuery object will cause unnecessary overhead;
  • By default, events are bound to the $ (document) element. If the DOM nested structure is deep, event bubbling causes performance loss through a large number of ancestor elements;
  • It can only be placed behind directly selected elements and cannot be used after the joined DOM Traversal method, that is, $ ("# info_table td "). live... yes, but $ ("# info_table "). find ("td "). live... no;
  • It is confusing to collect td elements and create jQuery objects, but actually operate on $ (document) objects.
Solution

To avoid generating unnecessary jQuery objects, you can use an hack called "Early delegate", that is, call. live () outside the $ (document). ready () method ():

Js Code  
  1. (Function ($ ){
  2. $ ("# Info_table td"). live ("click", function () {/* show more information */});
  3. }) (JQuery );

 

Here (function ($) {...}) (jQuery) is"Anonymous function executed immediately"And forms a closure to prevent name conflicts. Inside an anonymous function, the $ parameter references the jQuery object. This anonymous function will not be executed until the DOM is ready. Note: When using this hack, the script must be linked and/or executed in the head element of the page. The reason for choosing this time is that the document element is available at this time, and the entire DOM is far from being generated. It makes no sense to put the script in front of the ending body Tag, at that time, DOM was fully available.

To avoid the performance loss caused by event bubbling, jQuery supports using a context parameter when using the. live () method from 1.4:

Js Code  
  1. $ ("Td", $ ("# info_table") [0]). live ("click", function () {/* show more information */});

In this way, the "trustee" is changed from the default $ (document) to $ ("# info_table") [0], saving the bubble journey. However. the context parameter used by live () must be a separate DOM element. Therefore, $ ("# info_table") [0] is used to specify the context object. it is a DOM element obtained by using the index operator of the array.

 

 

3. delegate ()

As mentioned above, in order to break through the limitations of a single. bind () method and implement event delegation, jQuery 1.3 introduces the. live () method. Later, in order to solve the problem that the "event propagation chain" is too long, jQuery 1.4 also supports specifying context objects for the. live () method. To solve the problem of unnecessary element set generation, jQuery 1.4.2 directly introduces a new method. delegate ().

 

When using. delegate (), the preceding example can be written as follows:

Js Code  
  1. $ ("# Info_table"). delegate ("td", "click", function () {/* show more information */});

 

The use of. delegate () has the following advantages (or solves the following problems of the. live () method ):

  • Bind the target element selector ("td"), event ("click"), and handler directly to the "dragged" $ ("# info_table, no additional elements are collected, the event Propagation Path is shortened, and the semantics is clear;
  • You can call the concatenation DOM Traversal method, that is, $ ("table"). find ("# info"). delegate... is supported, and precise control is supported;

The. delegate () method is a perfect solution. However, when the DOM structure is simple, you can also use. live ().

Tip: When you use event delegation, if other Event Handlers registered to the target element use. stopPropagation () to prevent event propagation, the event Delegate will become invalid.

 

Undelegate ():Remove delegate binding

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.