Details about JS event binding, event listening, and event delegation. js details

Source: Internet
Author: User

Details about JS event binding, event listening, and event delegation. js details

In JavaScript learning, we often encounter JavaScript event mechanisms, such as event binding, event listening, and event delegation (event proxy. What do these terms mean? What are their functions?

Event binding

To allow JavaScript to respond to user operations, you must first bind the event handler function to the DOM element. The so-called event processing function is the function that processes user operations. Different operations correspond to different names.

In JavaScript, there are three common methods to bind events:

  1. Bind directly to DOM elements;
  2. Binding in JavaScript code;
  3. Bind the event listening function.

Bind events directly in the DOM

We can bind the onclick, onmouseover, onmouseout, onmousedown, onmouseup, ondblclick, onkeydown, onkeypress, and onkeyup on DOM elements. Many of them are not listed one by one. For more event types, see DOM events.

<input type="button" value="click me" onclick="hello()"><script>function hello(){ alert("hello world!");}</script>

Bind events in JavaScript code

Binding events in JavaScript code (that is, within the script tag) can separate JavaScript code from the HTML Tag. The document structure is clear and easy to manage and develop.

<input type="button" value="click me" id="btn"><script>document.getElementById("btn").onclick = function(){ alert("hello world!");}</script>

Use event listening to bind events

Another way to bind events is to use addEventListener () or attachEvent () to bind the event listening function. The following is a detailed description of event listening.

Event listening

For event listening, the W3C Specification defines three event phases, namely the capture phase, the target phase, and the bubble phase.

At first, Netscape developed a JavaScript event-driven mechanism (event capture ). Then IE also launched its own event-driven mechanism (event bubbling ). At last, W3C standardizes two types of event mechanisms, including the capture, target, and bubble phases. IE8 has always adhered to its own event mechanism (front-end staff have always had a headache with compatibility issues). IE9 and later IE also supported W3C specifications.

W3C Specification

Syntax:

Element. addEventListener (event, function, useCapture)

Event: (required) event name. All DOM events are supported.

Function: (required) specifies the function to be executed when an event is triggered.

UseCapture: (optional) Specifies whether an event is executed in the capture or bubble phase. True, capture. False: Bubble. The default value is false.

Note: IE8 is not supported.

<input type="button" value="click me" id="btn1"><script>document.getElementById("btn1").addEventListener("click",hello);function hello(){ alert("hello world!");}</script>

IE Standard

Syntax:

Element. attachEvent (event, function)

Event: (required) event type. You need to add "on", for example, onclick.

Function: (required) specifies the function to be executed when an event is triggered.

<input type="button" value="click me" id="btn2"><script>document.getElementById("btn2").attachEvent("onclick",hello);function hello(){ alert("hello world!");}</script>

Advantages of event listening

1. You can bind multiple events.

<Input type = "button" value = "click me" id = "btn3"> <script> var btn3 = document. getElementById ("btn3"); btn3.onclick = function () {alert ("hello 1"); // not executed} btn3.onclick = function () {alert ("hello 2 "); // execution} </script>

The regular event binding only executes the last Bound event.

<input type="button" value="click me" id="btn4"><script>var btn4 = document.getElementById("btn4");btn4.addEventListener("click",hello1);btn4.addEventListener("click",hello2);function hello1(){ alert("hello 1");}function hello2(){ alert("hello 2");}</script>

Both events are executed.

2. You can unbind the corresponding binding.

<Input type = "button" value = "click me" id = "btn5"> <script> var btn5 = document. getElementById ("btn5"); btn5.addEventListener ("click", hello1); // btn5.addEventListener ("click", hello2) is executed; // btn5.removeEventListener ("click ", hello2); function hello1 () {alert ("hello 1");} function hello2 () {alert ("hello 2") ;}</script>

Encapsulate event listening

<Input type = "button" value = "click me" id = "btn5"> // bind the listening event function addEventHandler (target, type, fn) {if (target. addEventListener) {target. addEventListener (type, fn);} else {target. attachEvent ("on" + type, fn) ;}// remove the listening event function removeEventHandler (target, type, fn) {if (target. removeEventListener) {target. removeEventListener (type, fn);} else {target. detachEvent ("on" + type, fn) ;}// test var btn5 = document. getElementById ("btn5"); addEventHandler (btn5, "click", hello1); // Add event hello1addEventHandler (btn5, "click", hello2 ); // Add event hello2removeEventHandler (btn5, "click", hello1); // remove event hello1

Event Delegate

Event delegation uses the principle of bubbling to add events to parent or ancestor elements to trigger execution results.

<input type="button" value="click me" id="btn6">var btn6 = document.getElementById("btn6");document.onclick = function(event){ event = event || window.event; var target = event.target || event.srcElement; if(target == btn6){ alert(btn5.value); }}

The above is just an example, and the code is simplified as much as possible. In actual code, we may use jQuery live (), delegate (), bind (), on (), and so on.

Advantages of event Delegation

1. Improve JavaScript performance. Event delegation can significantly increase event processing speed and reduce memory usage. The event Delegate and event binding in the example analysis JavaScript are well written in this article.

Traditional writing

<ul id="list"> <li id="item1" >item1</li> <li id="item2" >item2</li> <li id="item3" >item3</li></ul><script>var item1 = document.getElementById("item1");var item2 = document.getElementById("item2");var item3 = document.getElementById("item3");item1.onclick = function(){ alert("hello item1");}item2.onclick = function(){ alert("hello item2");}item3.onclick = function(){ alert("hello item3");}</script>

Event Delegate

<ul id="list"> <li id="item1" >item1</li> <li id="item2" >item2</li> <li id="item3" >item3</li></ul><script>var item1 = document.getElementById("item1");var item2 = document.getElementById("item2");var item3 = document.getElementById("item3");document.addEventListener("click",function(event){ var target = event.target; if(target == item1){ alert("hello item1"); }else if(target == item2){ alert("hello item2"); }else if(target == item3){ alert("hello item3"); }})</script>

2. dynamically add DOM elements without modifying event binding because of element changes.

Traditional writing

<ul id="list"> <li id="item1" >item1</li> <li id="item2" >item2</li> <li id="item3" >item3</li></ul><script>var list = document.getElementById("list");var item = list.getElementsByTagName("li");for(var i=0;i<item.length;i++){ (function(i){ item[i].onclick = function(){ alert(item[i].innerHTML); } })(i)}var node=document.createElement("li");var textnode=document.createTextNode("item4");node.appendChild(textnode);list.appendChild(node);</script>

When you click item1 to item3, there is an event response, but when you click item4, there is no event response. It means that the traditional event binding cannot dynamically add events to the dynamically added elements.

Event Delegate

<ul id="list"> <li id="item1" >item1</li> <li id="item2" >item2</li> <li id="item3" >item3</li></ul><script>var list = document.getElementById("list");document.addEventListener("click",function(event){ var target = event.target; if(target.nodeName == "LI"){ alert(target.innerHTML); }})var node=document.createElement("li");var textnode=document.createTextNode("item4");node.appendChild(textnode);list.appendChild(node);</script>

When item4 is clicked, item4 has an event response. The event Delegate can dynamically add events for newly added DOM elements.

I hope this article will help you. Thank you for your support!

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.