On the event binding of JavaScript

Source: Internet
Author: User
Tags bind closure
About the JavaScript event binding on the Internet has been a lot of relevant information, today this article is also asked by colleagues in the way to record it, is a JavaScript event binding a small skill, if you can in the work of good use, will have the effect of surprise

In fact, there is no new knowledge, just for the convenience of other needy friends to read, for their own is also an accumulation, so can only be called chat JavaScript, old birds can enjoy drifting.
Before you get to the point, ask a question to warm up.
Now you have the following HTML structure:

Copy Code code as follows:


<div id= "wrap" >


<input type= "button" value= "buttons One"/>


<input type= "button" value= "buttons two"/>


<input type= "button" value= "buttons three"/>


<input type= "button" value= "buttons four"/>


<input type= "button" value= "buttons five"/>


</div>


and the following JavaScript code:

Copy Code code as follows:


var wrap = document.getElementById (' wrap '),


inputs = wrap.getelementsbytagname (' input ');





for (var i = 0, L = inputs.length i < l i++) {


Inputs[i].onclick = function () {


alert (i);


    }


}


Excuse me, what is the result of this implementation?
/*************************** Split Line ***************************/
If your answer is "click on the button, Alert's index value of the current button", then you're in my trap. You may wish to try, no matter which button you click, it will alert (5).

Why is this seemingly natural outcome different from the actual situation? In fact, it is also very well understood.
Since onclick is just an event binding, not an execution, when we execute the onclick event, then I is already the value of the loop, so it's no surprise that each button is alert (5).

So, what if we were to implement the "click button", Alert's index value of the current button? Here is a concept called "closure" with a hidden mystery in JavaScript. We can rewrite the above JS in the way of closure and save the I value in memory in the For loop with the following code:

Copy Code code as follows:


var wrap = document.getElementById (' wrap '),


inputs = wrap.getelementsbytagname (' input ');





for (var i = 0, L = inputs.length i < l i++) {


(function (cur) {


Inputs[cur].onclick = function () {


alert (cur);


        }


}) (i)


}


Try the effect again? You can really alert the corresponding index value, but so far is only appetizer, the topic has just begun!
The above method, we tie the event to the button by looping + closures, and we know that in JavaScript the function is also an object, the object takes up memory, and now there are only 5 buttons in the example, and you might think that the performance overhead would be negligible, but if we had 50, Even 500 buttons, IE has been crying, when there are more other performance vulnerabilities concurrency, all browsers are crying.

Back to the example, we can use the "event delegate" approach to solve the performance problems that can result from binding events as the button increases. The principle is very simple, using Javascript event bubbling, we can move the binding of events from buttons to their parent elements, regardless of the number of buttons, they have only a common parent element, so we only need to bind an event on it.
The code is as follows:

Copy Code code as follows:


var wrap = document.getElementById (' wrap '),


Inputs = wrap.getelementsbytagname (' input ');





Wrap.onclick = function (ev) {


var ev = EV | | Window.event,


target = Ev.target | | Ev.srcelement;


for (var i = 0, L = inputs.length i < l; i++) {


if (inputs[i] = = target) {


alert (i)


        }


    }


}


At this point, after dinner, we can go further, to some dessert.
In addition to performance, event delegates are more advantageous than event bindings for closures, and event delegates do not have to take into account the number of child elements (that is, elements of the bound event). For example, we add a button after the OnClick event is bound :

Copy Code code as follows:


var newinput = document.createelement (' input ');


newinput.setattribute (' type ', ' button ');


Newinput.setattribute (' Value ', ' button Six ');


Wrap.appendchild (newinput);


Also at the end of this code with the closure and event delegation, we can see that the closure implementation of the event binding click "button Six" has no effect, but in the event delegate implementation of the event binding fixed-point hit "button Six" will have alert. Instead, if we're going to delete a button, the closure will still hold the onclick event of the deleted button in memory (unless manually set to null), and the event delegate will not burden the memory unnecessarily, and for this reason, we should also use the event delegate to bind multiple elements of the same level.

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.