JS event binding, event monitoring, event delegation Detailed introduction _ Basic knowledge

Source: Internet
Author: User
Tags event listener script tag

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 is the effect?

Event Bindings

To allow JavaScript to respond to the user's actions, you first bind the event handler function to the DOM element. The so-called event-handling function, is to handle the user action functions, different operations corresponding to different names.

In JavaScript, there are three common methods of binding events:

    1. Directly bound in a DOM element;
    2. Binding in JavaScript code;
    3. Binding event listener function.

Binding events directly in the DOM

We can bind the DOM elements to the onclick, onmouseover, onmouseout, onmousedown, onmouseup, ondblclick, onkeydown, onkeypress, onkeyup, and so on. Many of them are not listed. If you want to know more event types, see the DOM event.

<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 (that is, inside the script tag) allows JavaScript code to be separated from HTML tags, with clear document structure and easy management and development.

<input type= "button" value= "click Me" id= "btn" >

<script>
document.getElementById ("btn"). onclick = function () {
 alert ("Hello world!");
}
</script>

Using events to listen for binding events

Another way to bind events is to bind the event listener with either AddEventListener () or attachevent (). The following detailed description, event monitoring.

Event Monitoring

With regard to event monitoring, the 3 event phases are defined in the standard, which is the capture phase, the target stage, and the bubbling phase.

At first Netscape developed a set of JavaScript event-driven mechanisms (that is, event capture). Then IE also launched its own set of event-driven mechanisms (that is, event bubbling). Finally, the two kinds of event mechanisms are regulated by the consortium, which is divided into capture stage, target stage and bubbling stage. IE8 before IE has been adhering to its own event mechanism (front-end staff has been a headache compatibility problem), IE9 after IE also supported the standard of the consortium.

The standard of the Consortium

Grammar:

Element.addeventlistener (event, function, Usecapture)

Event: (required) The name of the incident that supports all DOM events.

Function: (required) Specifies the functions to be executed when the event is triggered.

Usecapture: (optional) Specifies whether the event is executed during the capture or bubbling phase. True, captured. False, bubbling. Default false.

Note: IE8 below 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

Grammar:

Element.attachevent (event, function)

Event: (required) events type. Need to add "on", for example: OnClick.

Function: (required) Specifies the functions 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>

The advantages of event monitoring

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");//Do not execute
}
Btn3.onclick = function () {
 alert ("Hello 2");
}
</script>

A regular event binding performs only 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>

All two 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);//execute
btn5.addeventlistener ("click", Hello2);
Btn5.removeeventlistener ("click", Hello2);

function Hello1 () {
 alert ("Hello 1");
}
function Hello2 () {
 alert ("Hello 2");
}
</script>

Encapsulation Event Monitoring

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

//Binding Listener Event
function addEventHandler (TARGET,TYPE,FN) {
 if (target.addeventlistener) {
 target.addeventlistener (TYPE,FN);
 } else{
 target.attachevent ("on" +TYPE,FN);
 }

Remove Listener 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 Hello1
addeventhandler (btn5, "click", Hello2);//Add Event Hello2
removeEventHandler (Btn5, "click", Hello1);//Removal event Hello1

Event delegates

Event delegates use the principle of bubbling to add events to the parent element or ancestor element, triggering 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 as simple as possible. In the actual code we may use the jquery Live (), delegate (), bind (), on (), and so on.

Event Delegate Benefits

1, improve JavaScript performance. Event delegates can significantly improve the processing speed of events and reduce memory footprint. Instance to parse event delegates and event bindings in JavaScript, and this article is pretty well written.

Traditional wording

<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 delegates

<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, dynamic Add DOM elements, do not need to change the element because of changes in the event binding.

Traditional wording

<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 you click Item4, there is no event response. Demonstrates that traditional event bindings cannot dynamically add events to dynamically added elements.

Event delegates

<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 Item4, ITEM4 has an event response. Explains that event delegates can add events dynamically for newly added DOM elements.

Through this article, I hope to help everyone, thank you for your support to this site!

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.