Event Binding, Event Monitoring, Event Delegation

Posted by ah66533 on Sat, 18 May 2019 06:08:46 +0200

In JavaScript learning, we often encounter JavaScript event mechanisms, such as event binding, event monitoring, event delegation (event broker), and so on. What do these nouns mean and what do they do?

Event binding

To make JavaScript responsive to user actions, you first need to bind event handlers to DOM elements. The so-called event handler is a function that handles user operations. Different operations correspond to different names.

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

  • Direct binding in DOM elements;
  • Binding in JavaScript code;
  • Bind event listener functions.

Binding events directly in DOM

We can bind onclick, onmouseover, onmouseout, onmousedown, onmouseup, ondblclick, onkeydown, onkeypress, onkeyup on DOM elements. There are many different lists. If you want to know more types of events, please check them. DOM incident.

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

Binding events in JavaScript code

Binding events in JavaScript code (i.e. within script tags) can separate JavaScript code from HTML tags, make the document structure clear, and facilitate management and development.

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

Use Events to Listen for Binding Events

Another way to bind events is to use addEventListener() or attachEvent() to bind event listener functions. The following details, event monitoring.

event listeners

With regard to event monitoring, the W3C specification defines three event stages: capture stage, target stage and bubble stage.

Initially Netscape developed JavaScript's event-driven mechanism (event capture). IE then launched its own event-driven mechanism (event bubbles). Finally, W3C regulates two event mechanisms, including capture stage, target stage and bubbling stage. Before IE 8, IE had always insisted on its own event mechanism (compatibility problems for front-end personnel). After IE 9, IE also supported the W3C specification.

W3C specification

Syntax:

element.addEventListener(event, function, useCapture)

event: (required) event name, all supported DOM incident.
Function: (required) Specify the function to be executed when the event is triggered.
useCapture: (optional) Specifies whether the event is executed during the capture or bubbling phase. true, capture. False, bubbles. Default false.

Note: IE8 is not supported below.

<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. Need to add "on", for example: onclick.
Function: (required) Specify the function to be executed when the 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 monitoring

1. Multiple events can be bound.

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

Conventional 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 were executed.

2. Removal of the corresponding binding

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

Encapsulated event monitoring

<input type="button" value="click me" id="btn5">
//Binding listening events
function addEventHandler(target,type,fn){
	if(target.addEventListener){
		target.addEventListener(type,fn);
	}else{
		target.attachEvent("on"+type,fn);
	}
}
//Remove listening events
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 hello1
addEventHandler(btn5,"click",hello2);//Add event hello2
removeEventHandler(btn5,"click",hello1);//Remove event hello1

Event delegation

Event delegation is to use the bubbling principle to add events to parent or ancestor elements and trigger the execution effect.

<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. The code is as simplified as possible. In practical code, we may use jQuery's live(), delegate(), bind(), on() and so on.

Advantages of Event Delegation

1. Improving JavaScript performance. Event delegation can significantly improve the processing speed of events and reduce memory usage. Example Analysis of Event Delegation and Event Binding in JavaScript This article is well written.

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 delegation

<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. Adding DOM elements dynamically does not require 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>

Clicking item1 to item3 has an event response, but when clicking item4, there is no event response. It shows that traditional event binding can not dynamically add events to dynamically added elements.

Event delegation

<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 you click on item4, item4 has an event response. Explains that event delegation can dynamically add events for newly added DOM elements.

Topics: Javascript IE JQuery