Some thoughts on the event binding of jquery

Source: Internet
Author: User

Event binding for jquery
Problem
First, let's look at one of the following very common event binding codes:

//example$(‘#dom‘).click(function(e){  //do something});$(‘#dom2‘).click(function(e){  //do something});

This code has some drawbacks with event binding processing:

Excessive event binding can deplete memory
Post-build HTML will have no event bindings and need to be re-bound
The grammar is too complicated
Solution Solutions
For the 1, 22-point solution, let's first look at jquery's event bindings

The event bindings for jquery have several methods that can be called, with the Click event as an example:

click Method
Bind method
Delegate method
On method
Regardless of the method you use (click/bind/delegate), it is ultimately the jquery bottom that calls the on method to complete the final event binding. So from a certain point of view in addition to the ease of writing and custom selection, it is better to directly use the on method to the happy and direct.

For a detailed explanation of the methods and use cases, please visit the jquery official website, which is not described here.

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

For performance analysis, Chrome's developer Tools will be used.
Profiles–> take Heap Snapshot, with this tool we can see the memory occupied by JavaScript, can analyze the performance problem.

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>      <!-- ...-      <li><a href="javascript:;" >Text</a></li>    </ul>  </body></html>

Method 1

$(function(){    $(‘.ul a‘).click(function(e){        alert(‘click event‘);    });});

The following is a memory analysis diagram of Method 1

Memory consumption approx. 3.4M

Method 2

$(function(){    $(‘.ul‘).on(‘click‘‘a‘function(e){        alert(‘click event‘);    });});

The following is a memory analysis diagram of Method 2

Memory consumption approx. 2.0M

Conclusion
Method 1 Obviously consumes 1.4M more memory than Method 2.
Method 1 cannot bind an event to a new DOM by clicking the button, and Method 2 can.
As long as on the delegate object is the original element of the HTML page, because the event is triggered by the JavaScript event bubbling mechanism to monitor, so for all child elements (including the later through JS generated elements) all the event monitoring can be effective, And because there is no event binding on multiple elements (2000+a tag in this example), memory loss can be effectively saved.

Thinking
Code like poetry, but it's easy to turn into code like crap. How to improve the elegance of your code is also a very interesting thing.

The following is a very common and popular JS file code snippet (for the general web site)

$(‘#btn-add‘).click(function(){  //do something});$(‘.action-box #btn-delete‘).click(function(){  //do something});$(‘.action-box #btn-sort‘).mouseenter(function(){  //do something});

It is no exaggeration to say that when a JS file is hundreds of lines, similar to the above code, you can hardly find the law from the inside.

Maybe a likes to write #btn-add, while B likes to write. Action-box #btn-add as a selector.
There are many different types of events, not a single sequence.
Didn't apply to what we just said. Use event bubbling to do event binding

Improved
Let's take a step further and improve the previous JS code

Version 1

$(‘.action-box‘).on(‘click‘‘#btn-add‘function(){  //do something});$(‘.action-box‘).on(‘click‘‘#btn-delete‘function(){  //do something});

Although the use of event bubbling, but the feeling is a little cumbersome,. Action-box appeared many times, feel uncomfortable, let us 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  }});

The feeling is much better, but still need to judge the elements to make corresponding treatment, acceptable, but not perfect.

Inspiration
First look at the enhanced version of CSS Sass for the above improvements in CSS syntax

/*bed CSS code*/. Action-box{width: %; Color: #000;}#btn-add{Color: Blue;}#btn-delete{Color: red;}/*good CSS code*/. Action-box{width: %; Color: #000;}. Action-box #btn-add{Color: Blue;}. Action-box #btn-delete{Color: red;}/*sass code*/. Action-box{width: %;  Color: #000;  #btn-add{Color: Blue;}#btn-delete{Color: red;}}

Copy Code
We can see the structure of the document in good CSS code and Sass Code, which can be clearly understood:. Action-box There are two buttons below.

Does this enable SASS to use this code structure in JS? The answer, of course, is yes.

$(‘.action-box‘).coffee({  click: {    ‘#btn-add‘function(){      //do something    },    //这是是支持jQuery的‘:last / [attr] / :eq(0)‘等方法的     ‘#btn-delete‘function(){      //do something    }  },  mouseenter: {    ‘#btn-sort‘function(){      //do something    }  }});

Do you like this structure?

Clear and concise document structure
Use event bubbling to effectively reduce memory usage
The first level is divided by the event name.
The property name of the second level is equivalent to the selector character.
Source Code of COFFEE function

function(obj){  for(varin obj)    for(varin obj[eName])      $(this).on(eName, selector, obj[eName][selector]);}

Talk about a few lines of code, you can make a wonderful grammar sugar

Enjoy yourself! ^_^

If you think this article is good, please help click on the recommendation, thank you!

Some thoughts on the event binding of 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.