Event mechanism (event bubbling and event capture)

Source: Internet
Author: User

<div id="outer">    <p id="inner">Click me!</p></div>
Event bubbling

Microsoft has proposed an event stream called event bubbling. Time bubbling means that events start from the most inner element and propagate upward until the document object.

So the above example takes place under the concept of event bubbling. The order of the click events should be HTML --

Event capture

Netscape proposes another event stream named event capturing. In contrast to event bubbling, events start from the outermost layer until the most specific element.

In the above example, the order in which the Click event takes place under the concept of event capture should be the page, HTML --

Netscape Navigator many elements on the page are not leaked to the event

In the DOM event flow, the event flow defined in the "DOM2 level event" supports both the event capture phase and the event bubbling phase

Insert a small fragment to explain the Dom2 level event here.

There are three ways of using event handlers:

1. HTML Event handlers

such as:<div  id=   < Span style= "FONT-SIZE:14PX;" ><,  p  id=   "inner" onclick= "alert (" I am an HTML event handler ");" >click me!  </ p>,  </ div>  


2, DOM0-level event handlers
如:<div id="outer"> <p id="inner">Click me!</p></div>
<script type="text/javascript">
var pBtn=document.get
ElementById("inner");

pBtn.onclick=function(){
}

</script>

3,DOM2 level events

  Is the use of AddEventListener () and other types of event processing on the IE and Dom are also different,

  The binding event in IE is reconciled to attachevent (), DetachEvent (),

  AddEventListener () in the DOM, RemoveEventListener ()

So how to be compatible with this problem? The following code, through if: else type judgment

 <Body>      <DivID= "box">         <inputtype= "button"value= "button"ID= "BTN"onclick= "Showmes ()">         <inputtype= "button"value= "button 2"ID= "BTN2">         <inputtype= "button"value= "button 3"ID= "Btn3">         <ahref= "event.html"ID= "Go">Jump</a>      </Div>   </Body>
HTML

varEventutil={             //Add HandleAddHandler:function(element,type,handler) {if(Element.addeventlistener) {Element.addeventlistener (Type,handler,false); }Else if(element.attachevent) {element.attachevent (' On ' +Type,handler); }Else{element[' On ' +type]=handler; }             },             //Delete handleRemoveHandler:function(element,type,handler) {if(Element.removeeventlistener) {Element.removeeventlistener (Type,handler,false); }Else if(element.detachevent) {element.detachevent (' On ' +Type,handler); }Else{element[' On ' +type]=NULL; }}, GetEvent:function(event) {returnEvent?event:window.event; }, GetType:function(event) {returnEvent.type; }, GetElement:function(event) {returnEvent.target | |event.srcelement; }, Preventdefault:function(event) {if(Event.preventdefault) {event.preventdefault (); }Else{Event.returnvalue=false; }}, Stoppropagation:function(event) {if(event.stoppropagation) {event.stoppropagation (); }Else{event.cancelbubble=true; }         }  }
JS
window.onload=function() {  var go=document.getelementbyid (' Go '),      box =document.getelementbyid (' box ');  Eventutil.addhandler (box,' click ',function() {      alert (' I am the whole parent box ');  });  Eventutil.addhandler (Go,' click ',function(e) {      //e= Eventutil.getevent (e);      e=e | | window.event;      Alert (Eventutil.getelement (e). nodeName);      Eventutil.preventdefault (e);      Eventutil.stoppropagation (e);  });
JS

Application Examples:

<UlId="Color-list" ><li>red</ li> <li>yellow </li> < li>blue</li> <li>green</ li> <li>black </li> < li>white</li> </UL>          

If you click on the LI element in the page and then output the colors in Li, we usually write this:

 (function () {var color_list = document.getelementbyid ( " Color-list '); var colors = color_list.getelementsbytagname ( ' Li '); for (var i=0;i<colors.length;i++) { Colors[i].addeventlistener ( ' click ', Showcolor,false); Span class= "hljs-function" >function showcolor (e) {var x = e.target; alert (" the color is "+ x.innerhtml); };}) (); 
/span>

This kind of code is normal, but if there are hundreds of elements on the page that need to be bound (assuming), then it must be bound hundreds of times.
So the problem arises:

First: A lot of event binding, performance consumption, but also need to unbind (ie will leak) Second: Bound elements must exist third: post-generation HTML will have no event binding, need to rebind fourth: The syntax is too complicated

In actual development, we can use a method called event broker, which uses the characteristics of the event stream.

Using the nature of the event stream, we can only bind an event handler function to complete:

  (function () {var color_list = document.getelementbyid ( ' click ', Showcolor,false); function showColor (e) {var x = e.target; if (x.nodename.tolowercase () = = =  ' Li ') {alert (" the color is ' + x.innerhtml); } }})(); 

The benefit of using event proxies is not only to reduce the number of event handlers to one, but also to have different ways of handling different elements. If other elements are added to the above list elements (such as: A, span, etc.), we do not have to cycle through each element to bind the event, directly modify the event handler function.

How do you use it in jquery?

Specifically, the event delegate is the event object itself that does not handle the event, but instead delegates the processing task to its parent element or ancestor element, or even the root element (document)

Entrusted with such a good feature of course jquery will not let go, so it is derived from. bind (),. Live (). On () and. Delegate (), jquery event bindings have several methods that can be called, with the Click event to illustrate:

Click Method The Bind method delegate method on method

Here's a clear idea: regardless of which method you use (click/bind/delegate), it is ultimately the jQuery bottom that calls the on method to complete the final event binding. So from a certain point of view in addition to the ease of writing and custom selection, it is better to directly use the on method to the happy and direct.

So in the new version of the API, this is written:

The. On () method event handler to the element in the currently selected JQuery object. In jquery 1.7, the. On () method provides all the functions of binding event handling, the effect is self-evident, in addition to the performance differences, through the delegate event can also be very friendly to support dynamic binding, as long as on the delegate image is the original HTML page elements, Because event triggering is monitored by JavaScript's event bubbling mechanism, all event monitoring can be effective for all child elements (including elements that are generated later by JS), and can effectively save memory loss due to the absence of event binding to multiple elements.

Event mechanism (event bubbling and event capture)

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.