Summary of JS event listening mechanism (event capture)

Source: Internet
Author: User
Tags event listener unique id

In the front-end development process, we often encounter the issue of adding events to the page elements, adding the event JS method is also many, there are directly added to the page structure, there is a use of some JS event monitoring method, because each browser to event bubbling event monitoring mechanism different, le browser only event bubbling, There is no mechanism for event monitoring, and the compatibility of event monitoring is the biggest challenge:

1. Write the method of the event directly on the page structure

function Eventfun () {//console.log (this)} <input type= "button" onclick= "Eventfun ()" value= "button"/>// Here is a question about the this scope, Eventfun here is a global function, the object is [objects Window],this pointing to the Window.

  

To resolve an issue with this scope, you can use the method that adds an event variable for the global function to pass the This object as a parameter to the function inside the page structure

<input type= "button" onclick= "eventfun2 (This)" value= "Button2"/> function eventfun2 (Eve) {// Here the event object is passed as a parameter to the global method Eve.name= "Alex"; Window.name= "Robin"; Console.log (this);//[object window] Console.log (Eve);//[Object Htmlinputelement] Console.log (this.name);//Robin Console.log (eve.name);//Alexvar Self=eve; Console.log (this.name);//robin Console.log (self.name);//alex alert (window.name); alert (self.name); }

  

2. The method used to assign a value to an event property is a method that binds to the event, but the limitation of this method is that only one method can be bound to the event, and if more than one is bound, the later method will prevail.

Htmlelementobject.onclick = Fucntion () {//Use this method of assigning values to an event property, this pointer points to the Window object, not to the event object, so this method is a reference

JS code fun1 (); Fun2 (); Fun3 (); Console.log (this);//window.object} function DoSomething () {//JS code} Htmlelementobject.onclick = dosomething;// Using this form of assigning a value to an Event object property, the this pointer points to the event execution object Console.log (this);//htmlelementobject

  

3. Event propagation--bubbling and capturing
The DOM event standard defines two kinds of event streams, which are significantly different and may have a considerable impact on your application. The two streams of events are capture and bubbling, respectively. Like many web technologies, Netscape and Microsoft have implemented them differently before they become standards. Netscape chose to implement the capture event stream, and Microsoft implemented the bubbling event stream. Fortunately, the consortium uses both approaches, and most new browsers follow these two streams of events.
By default, events use the bubbling event stream and do not use the capture event stream. However, in Firefox and Safari, you can explicitly specify the use of the capture event stream by passing in the Usecapture parameter when registering an event and setting this parameter to True.
Bubbling event Stream
When an event is triggered on a DOM element, such as when a user clicks on the client's name node, the event will bubble through the entire DOM node hierarchy as the parent node inherits from the node, until it encounters a node attached to the event type processor, which is the OnClick event at this time. The bubbling of events can be terminated at any time during the bubbling process, which can be done by invoking the Stoppropagation () method on the event object on the Internet Explorer can be set by setting the event object's Cancelbubble property to True. If you do not stop the propagation of an event, the event continues to bubble through the DOM until it reaches the document root.
Capturing event Streams
The processing of the event begins at the root of the DOM hierarchy, not from the target element that triggers the event, and the event is passed down from all ancestor elements of the target element. In this process, events are captured from the document root to the elements of each inheritance derivation between the event target elements, and if the event listener is registered with the Usecapture property set to True, then they can be assigned to any element of the period to handle the event; The event is then passed to the next element on the path of the derived element until the target element. When the event reaches the target element, it then bubbles through the DOM node.
Modern Event Binding method
As discussed in the previous lesson, there are many drawbacks to using traditional event bindings, such as the inability to register multiple event handlers on the same event for an object. The browser and the Web do not take this into account, so in modern browsers, they have their own way of binding events.
The DOM of the Consortium
Obj.addeventlistener (evtype,fn,usecapture)--W3C provides a way to add an event handler function. Obj is the object to add the event, Evtype is the event type, without an on prefix, and FN is the event handler, and if Usecapture is true, the event handler is executed during the capture phase, otherwise in the bubbling phase
Obj.removeeventlistener (evtype,fn,usecapture)--W3C provides a way to delete event handler functions
Microsoft IE method
Obj.attachevent (EVTYPE,FN)--ie provides a way to add an event handler function. Obj is the object to add the event, Evtype is the event type, with an on prefix, and FN is the event handler, IE does not support event capture
Obj.detachevent (EVTYPE,FN,)--ie provides a way to delete event handlers, Evtype contains an on prefix

Ways to integrate both

function Addevent (obj,evtype,fn,usecapture) {if (Obj.addeventlistener) {Obj.addeventlistener (evtype,fn,usecapture) ; } else {obj.attachevent ("on" +EVTYPE,FN),//ie does not support event capture} else {obj["on" +evtype]=fn;//in fact this situation does not exist}} function delevent (obj , evtype,fn,usecapture) {if (Obj.removeeventlistener) {Obj.removeeventlistener (evtype,fn,usecapture);} else { Obj.detachevent ("on" +EVTYPE,FN); } else {obj["on" +evtype]=null;}}

  

The problem with the attach method of IE is that when you use attachevent, this points to window, not to obj!, in the event handler function. Of course, this one has a solution!

But the Attachevent method of IE has another problem, the same function can be registered to the same object on the same event multiple times, solution: Abandon IE attachevent Method! The Attachevent method under IE does not support capture, and the traditional event registration is not much different (in addition to the ability to bind multiple event handlers), and the Attachevent method of IE has a memory leak problem!
Addevent,delevent Modern Edition

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 

  

Summary of JS event listening mechanism (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.