Three common binding event methods in JS

Keywords: Javascript IE JQuery

In the study of JavaScript, we often encounter the event mechanism of JavaScript, such as event binding, event listening, event delegation (event agent), etc. What do these nouns mean and what are their functions?

Event binding

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

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

  1. Bind directly in DOM element;
  2. Binding in JavaScript code;
  3. Binding event listener function.

Binding events directly in DOM

We can bind onclick, onmouseover, onmouseout, onmousedown, onmouseup, ondbllick, onkeydown, onkeypress, onkeyup, etc. on DOM elements. Many are not listed one by one. If you want to know more about event types, check out DOM events.

<input type="button" value="click me" onclick="hello()">

<script>
function hello(){
 alert("hello world!");
}

Binding events in JavaScript code

Binding events in JavaScript code (that is, 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!");
}

Use events to listen for binding events

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

event listeners

As for event monitoring, the W3C specification defines three event stages, namely capture stage, target stage and bubble stage.

At first, Netscape developed a set of event driven mechanism (event capture) for JavaScript. Then ie also launched its own set of event driven mechanism (that is, event bubbling). In the end, W3C standardizes two kinds of event mechanism, including capture stage, target stage and bubbling stage. Before IE8, ie had always insisted on its own event mechanism (the compatibility problem that front-end personnel have been worried about), and after IE9, ie also supported the W3C specification.

W3C specification

Syntax:

element.addEventListener(event, function, useCapture)

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

Function: (required) specifies the function to execute when the event is triggered.

useCapture: (optional) specifies whether the event is executed during the capture or bubbling phase. true, capture. False, bubbling. The default is 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!");
}

IE standard

Syntax:

element.attachEvent(event, function)

Event: (required) event type. Add "on", for example: onclick.

Function: (required) specifies the function to execute 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!");
}

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
}

The general 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");
}

Both events were executed.

2. You can unbind the corresponding

<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");
}

Encapsulate event listening

<input type="button" value="click me" id="btn5">

//Binding listening event
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 Hello 2
removeEventHandler(btn5,"click",hello1);//Remove event hello1

Thinking: why can't event binding execute multiple events (execute the last event); event listening can:

Answer: js does not support event overloading. Binding event is equivalent to the address of a function stored in a variable. If another event is bound, it is equivalent to the address of a variable pointing to another function

Event listening is equivalent to subscribing to the publisher, changing the data and triggering the event. The function subscribing to the event is executed

 

 

Event delegation

Event delegation is to use the bubbling principle to add events to the parent element or ancestor element to 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 the actual code, we may use jQuery's live(), delegate(), bind(), on(), etc.

Event delegation benefits

1. Improve JavaScript performance. Event delegation can significantly improve the processing speed of events and reduce the memory consumption. The example analyzes 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>

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");
}

Event delegation

<ul id="list">
 <li id="item1" >item1</li>
 <li id="item2" >item2</li>
 <li id="item3" >item3</li>
</ul>
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");
 }
})

2. Dynamic addition of DOM elements does not need to modify the event binding due to element changes.

Traditional writing

<ul id="list">
 <li id="item1" >item1</li>
 <li id="item2" >item2</li>
 <li id="item3" >item3</li>
</ul>
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);

There is an event response from clicking item1 to item3, but when clicking item4, there is no event response. It indicates that traditional event binding cannot add events dynamically 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>
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);

When you click item4, item4 has an event response. Explain that event delegation can dynamically add events for newly added DOM elements.

 

Thinking: why is the binding event of dynamically added elements invalid in js? Event delegation can

Published 56 original articles, won praise 2, visited 1709
Private letter follow

Posted by theycallmepj on Tue, 17 Mar 2020 02:55:45 -0700