Thoughts on jquery event binding

Source: Internet
Author: User
ArticleDirectory
    • Performance
    • Inspiration
Jquery event binding

First, let's look at a very common event binding below.Code:

 
//Example$ ('# Dom'). Click (Function(E ){//Do something}); $ ('# Dom2'). Click (Function(E ){//Do something});

This code has some defects in event binding:

    1. Excessive event binding will consume memory.
    2. There will be no event binding in the HTML generated later, and you need to re-bind it
    3. Too complex syntax
Solution

For the solution of and, first let's take a look at jquery's event binding

Multiple methods can be called to bind jquery events. The following uses the click event as an example:

    • Click Method
    • Bind Method
    • Delegate Method
    • On Method

No matter which method you use (click/bind/Delegate), the bottom layer of jquery is to call the on method to complete the final event binding. Therefore, from a certain point of view, in addition to the convenience and habits of writing, it is better to simply use the on method to make it easy and direct.

For more information about the methods and use cases, visit the official jquery website. Api.jquery.com

Performance

First, we need to have a clear understanding of the memory usage gap between different event binding methods.

Chrome developer tools will be used for performance analysis.
Profiles --> take heap snapshot. With this tool, we can see the memory occupied by JavaScript and analyze performance problems.

Demo html
 <  Html  >    <  Head  >     <  Script  Type  = "Text/JavaScript"  >  $ (  Function  () {$ (  '  # BTN-add  '  ). Click (  Function () {$ (  '  . UL  '  ). Prepend (  '  <Li> <a href = "javascript:;"> text </a> </LI>  '  );});});  </  Script  >   </  Head  >    <  Body  >      <  Button  ID  = "BTN-Add"  > Create Element </  Button  >      <  Ul  Class = "Ul"  >        <  Li  > <  A  Href  = "Javascript :;"  > Text </  A  > </  Li  >        <! --  2000 line...  -->       <  Li  > <  A  Href  = "Javascript :;"  > Text </  A  > </  Li  >      </  Ul  >    </  Body >  </  Html  > 
Method 1
 
$ (Function() {$ ('. UL A'). Click (Function(E) {alert ('Click event');});});

The following figure shows the memory Analysis of method 1.

    • Memory usage3.4 m

Method 2
 
$ (Function() {$ ('. U'). On ('click', 'A ',Function(E) {alert ('Click event');});});

The following figure shows the memory Analysis of method 2.

    • Memory usage2.0 m

Conclusion
    1. Method 1 is much more expensive than method 2.1.4 mMemory
    2. Method 1 cannot bind events to the DOM added by clicking the button, while method 2 can.

As long as the on delegate object is the original element of the HTML page, the event is triggered by monitoring through the event bubbling mechanism of JavaScript, therefore, event monitoring is effective for all subelements (including elements generated by JS later, in addition, you do not need to bind events to multiple elements (2000 + a tag in this example), which can effectively reduce memory consumption.

Thoughts

Code is like poetry, but it is easy to become code like shit. How to Improve code elegance is also very interesting.

The following is the code snippet of a common and common JS file (for general websites)

$ ('# BTN-add'). Click (Function(){//Do something}); $ ('. Action-box # BTN-delete'). Click (Function(){//Do something}); $ ('. Action-box # BTN-Sort'). mouseenter (Function(){//Do something});/** ** More same code*/

It is no exaggeration to say that when a JS file contains hundreds of lines, similar to the above Code, it is difficult for you to find the rule from it.

    1. Maybe a prefers to write# BTN-addB prefers to write. Action-box # BTN-add.
    2. There are many different types of events piled up, and there is no order at all.
    3. We didn't use the event bubbles we just talked about to bind events.

Improvement

Let's improve the previous JS Code step by step.

Version 1
 
$ ('. Action-box'). On ('click',' # BTN-add ',Function(){//Do something}); $ ('. Action-box'). On ('click',' # BTN-delete ',Function(){//Do something});

Although event bubbling is used, it still seems a little cumbersome,. Action-boxIt appears many times and it feels uncomfortable. Let's continue to improve.

Version 2
$ ('. Action-box'). On ('click',' # BTN-add, # BTN-delete ',Function(){If($ (This). ATTR ('id') = 'btn-add'){//Do something}Else{//Do something}});

It feels much better than just now, but it still needs to judge the elements to make corresponding processing, acceptable, but not perfect.

Inspiration

First, let's take a look at the improvement of the CSS enhanced version sass on the CSS syntax.

 /*  Bed CSS code  */  . Action-box {Width : 100% ; Color : #000 ;} # BTN-add { Color : Blue ;} # BTN-delete { Color : Red ;} /*  Good CSS code  */  . Action-box {Width : 100% ; Color : #000 ;} . Action-box # BTN-add { Color : Blue ;} . Action-box # BTN-delete { Color : Red ;} /*  Sass code  */  . Action-box { Width : 100% ; Color : #000 ; # BTN-add {color : Blue ;} # BTN-delete { Color : Red ;} } 

We canGood CSS codeAndSass codeThe document structure can be clearly indicated in detail: There are two buttons Under. Action-box.

Can sass code structure be applied to JS? The answer is yes, of course.

$ ('. Action-box'). Coffee ({Click :{'# BTN-add ':Function(){//Do something},//This method supports jquery methods such as ': Last/[ATTR]/: eq (0 )'.'# BTN-delete ':Function(){//Do something}}, Mouseenter :{'# BTN-Sort ':Function(){//Do something}}});

Do you like this structure?

    1. Clear document structure
    2. Use event bubbling to effectively reduce memory usage
    3. Level 1 is classified by event name
    4. The second-level attribute name is equivalent to the selector.
Coffee function source code
 
$. FN. Coffee =Function(OBJ ){For(VaREnameInOBJ)For(VaRSelectorInOBJ [ename]) $ (This). On (ename, selector, OBJ [ename] [selector]);}

Just talk about several lines of code to make it a wonderful one.Syntactic sugar

Enjoy yourself! Pai_^

If you think this article is not bad, please click here for recommendations. Thank you!

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.