An overview of event handling in DOM and a comprehensive analysis of its principles

Source: Internet
Author: User

An event is a way of implementing asynchronous programming, essentially a communication between the various components of a program, and DOM supports a large number of events;This article gives you a detailed analysis of the basic principles of event handling: Event type, event target, event handler, event object, event Propagation Finally, we introduce the event object; (original article, transfer please specify: Suse: http://www.cnblogs.com/susufufu/p/5768431.html) One, event type : is a full lowercase string that describes what type of event occurred, such as ' MouseOver 'Traditional Event types: Form events, window events, mouse events, keyboard events, DOM events, HTML5 events, touchscreen and mobile device events, and so on, here is a detailed description of all events: DOM Event type Ii. Event target : The object that triggered the event  Third, event handlers (or event listeners): functions that handle or respond to an event listener. When an object triggers an event, the browser automatically invokes the function registered on the object; Registering an event handler (Listener event): 1. Register as an HTML attribute (only triggered during the bubbling phase) such as <table id= "T" onclick= "Modifytext ();" >; Some event types are usually triggered directly on the browser, rather than triggered on any particular document element, and these event handlers are placed on the <body> tab, but the browser registers them on the Window object, such as <body onload= "alert (' Hello world! ') " These events are:onafterprint onfocus ononline onresize onbeforeprint onhashchangeonpagehide onstorage onbeforeunload onload onpageshow OnUndoonblur onmessage onpopstate onunload onerror onoffline OnredoThe value of the event as an HTML attribute is the JS code string, which is the body of the processing function, without {}, Note: Try not to register an event on any other HTML tag, it violates the principle that HTML is separated from JavaScript code, if the event function may not have been loaded in The event object element is clicked, which causes an error;2. Register as a property of the DOM element (only in the bubbling phase), at which time the name of the event handler property is prefixed with the ' on ' prefix, which is compatible with all browsers, the only drawback is that only one event handler function is registered, and if the onclick attribute is defined two times, the last definition overrides the previous Once, such as: Window.onload = function () {...};3. In addition to IE8 and previous versions of all browsers, DOM event operations (listening and triggering) are defined on the Eventtarget interface. The element node, document node, and window object are all deployed with this interface. In addition, the XMLHttpRequest, AudioNode, Audiocontext and other browser-built objects, also deployed this interface. The interface has three methods, AddEventListener and RemoveEventListener are used to bind and remove the listener function, dispatchevent to trigger the event;The AddEventListener (Type,listener,boolean) method registers the listener, and the third parameter sets the propagation mode of the event, usually using the default value of False, which indicates that the listener function is only in the bubbling phase (pupple) Trigger, when set to True, indicates that the listener function is triggered in the capture phase, can register any number of listener for the same type of event on the same object, and all listener will be triggered in the order of registration (the registered duplicate listener will be ignored by the browser); if you want to pass parameters to the listener function, you can wrap the listener function with an anonymous function, such as Elm.addeventlistener (' click ', function () {Listen (' argument ')},false);when the registered listener is a reference variable to a function, you can use Removeeventlestener (type,listener,boolean) to delete the listener on the event target, the bubbling event for the same listener event, and the catch The incident need to be deleted separately, the two do not interfere;var div = document.getElementById (' div ');var listener = function (event) {/ * Do something here * /                };div.addeventlistener (' Click ', Listener, false);div.removeeventlistener (' Click ', Listener, false);The dispatchevent (event) method triggers the execution of the listener function by manually triggering the specified event on the current node. The method returns a Boolean value that returns false if a listener function calls Event.preventdefault (), otherwise true, the argument is an instance of an event object that cannot be empty and must be a valid event object, otherwise an error is made; btn.addeventlistener (' Click ', Listener, false);var e = new Event (' click ');btn.dispatchevent (e);//The Click event is immediately triggered on BTN and will be called immediately listenerThe following example determines whether an event is canceled based on the return value of the Dispatchevent methodvar canceled =!btn.dispatchevent (event);if (canceled) {Console.log (' event cancellation ');}else {console.log (' event not canceled ');}}4.IE8 and previous versions only support Attachevent (Type,listener) and DetachEvent (Type,listener), their usage and AddEventListener differences: A. parameters only two; b. The reference The number type must be prefixed with ' on '; c. It allows duplicate registration of the same listener and is called; d. The disadvantage of using the Attachevent method is that the value of this will become the Window object instead of the element that triggered the event; Call Order issues : 1. Handlers that are registered by setting object properties or HTML properties are always called first;2. The handlers registered with AddEventListener are invoked in the order in which they are registered;3. Handlers registered with Attachevent in the older version of IE may be called in any order. return value problem : 1. The return value of the event handler is only meaningful for handlers registered through the property, and the return value of registering an event handler by setting an object property or HTML property is False, which tells the browser not to perform the default action associated with the event. When the browser is going to jump to a new page, the onbeforeunload Event of the Window object is triggered, and if its return value is a string, it will appear in the Query confirmation dialog box;2.addEventListener () or attachevent () register event handlers to cancel the browser's default action you must call the Preventdefault () method or set the event object's re The Turnvalue property. this points to the problem : The Listener function specified by the 1.addEventListener method, the internal this object always points to the node that triggered the event;The This of the event handler functions registered by 2.IE8 and the previous Attachevent method points to the global object;the This object in the following notation points to the element node. Element.onclick = print;element.addeventlistener (' Click ', Print, false)Element.onclick = function () {console.log (this.id);}<element onclick= "Console.log (this.id)" >The this object, which is the following notation, points to the global object. Element.onclick = function () {dosomething ()};element.setattribute (' onclick ', ' dosomething () ');<element onclick= "dosomething ()" >element.attachevent (' onclick ', dosomething)//ie8 Memory Problem : For the following code, a new anonymous function is created in each loop, which takes up more and more memory; it cannot be called because it is not persisted to a reference to an anonymous function RemoveEventListener ; Therefore, the second parameter listener should be kept as a reference to the processing event function;For (i=0; i<els.length; i++) {Els[i].addeventlistener ("click", Function (e) {/*do something*/}, false});                    } Common tool functions compatible with older versions of IE :ensure that the this event handler's this pointer to the event's target object's tool function Addeventfunction Addevent (target,type,func) {if (target.addeventlistener) {Target.addeventlistener (type,func,false);}else{target.attachevent (' on ' +type,function (e) {//Here Attachevent registered handler function unbound reference, so cannot be deleted with DetachEventreturn func.call (target,e);        });    }}//Common event handlers (because IE8 and previous versions, handlers for the on-property of the event target need to window.event to get the event object, and the target node object that triggered the event is obtained through the event.srcelement attribute)function func (event) {var event = event| | window.event;var target = Event.target | | event.srcelement;    //...... Handler Code}  Event Propagation: is the process by which the browser determines which object triggers its event handlers. The event flow defined by the "DOM2 level event" consists of three stages: the event capture phase ==> is in the target phase ==> event bubbling phase. The first occurrence is the event capture phase, which propagates from the outer layer to the inner layers, providing an opportunity for all nodes that propagate the event to intercept events. Then the actual target receives events (performed in the Order of registration). The final stage is the bubbling phase (bubbling from the inside to the outer layer). when the container element and nested elements, that is, during the capture phase and during the bubbling phase invoke the event handler: The event executes the event handler in the order of the DOM event stream, and when the event is in the target stage, the event invocation order is determined by the order in which the binding event is writtenThere are two ways to stop propagating an event to a node: 1. Use the Event.stoppropagation () method of the event object to block the propagation of the current listener function ; 2. Use the Event.stopimmediatepropagation () method of the event object to block the propagation of all the listener functions of the current event on its event object;Event Proxy (delegation): Because events propagate up to the parent node in the bubbling phase, the listener function of the node can be defined on the parent node, and the listener function of the parent node handles the events of multiple child elements uniformly;  Event Object : After an event occurs, an event object is generated and passed as a parameter to the listener function. The browser native provides an event object, all of which are instances of this object, or inherit the Event.prototype object. The event object itself is a constructor that can be used to generate a new instance. var ev = new Event ("look", {"Bubbles": true, "cancelable": false});document.dispatchevent (EV);The event constructor accepts two parameters. The first argument is a string that represents the name of the event, and the second argument is an object that represents the configuration of the event object. The parameter can have the following two properties. Bubbles: boolean, optional, default = False to indicate whether the event object is bubbling. cancelable: boolean, optional, default = False to indicate whether the event can be canceled. properties of the event object:1. Related to the stage of the event: Bubbles: A read-only property that returns a Boolean value that indicates whether the current event will bubble and invoke different functions depending on whether the event is bubbling. eventphase: Returns an integer value (one of the 0,1,2,3) that represents the state in which the event is currently located0, the event does not currently occur. 1, the event is currently in the capture phase, which is in the propagation process from the ancestor node to the target node. The process is from the Window object to the document node, and then to the Htmlhtmlelement node until the parent node of the target node. 2, the event reaches the target node, which is the node that the target property points to. 3, the event is in the bubbling phase, which is in the reverse propagation process from the target node to the ancestor node. The procedure is from the parent node to the Window object. This stage can only occur if the Bubbles property is True 2. Related to the default behavior of the event: cancelable: Returns a Boolean value that indicates whether the event can be canceled. If you want to cancel an event, you need to call the Preventdefault method on this event defaultprevented: Returns a Boolean value that indicates whether the event has called the Preventdefault method.  3. Related to the target node of the event: currenttarget: Returns the node to which the listener function executed by the event is bound. Target: Returns the node that triggered the event. In Ie6-ie8, the name of the attribute is not target, but srcelement 4. Related to other information about the event object: Type: Returns a String representing the event type Detail: Returns a numeric value that represents some kind of information for an event. The specific meaning relates to the event type, and for mouse events, the number of times the mouse button is pressed in a location, such as for the DblClick event, the value of the detail property is always 2 TimeStamp: Returns a millisecond timestamp indicating when the event occurred. Calculated from Performancetiming.navigationstart, which represents the time when the user navigates to the page. If you want to convert this value to the Unix epoch timestamp, calculate Event.timestamp + Performance.timing.navigationStart istrusted: Returns a Boolean value that indicates whether the event can be trusted. Not very useful, different browser support is not the same.   method of the event object: preventdefault(): Cancels the browser's default behavior for the current event, which assumes that the Cancelable property of the event is true and that if false, calling the method has no effect. stoppropagation(): The termination event is further propagated during the capture, target processing, or bubbling phase of the propagation process. After the method is called, the handler that handles the event on that node is called, and the event is no longer dispatched to the other node. Note: This method cannot prevent other event handles on the same Document node from being called, but it can prevent events from being dispatched to other nodes stopimmediatepropagation(): The other listener functions that prevent the same event are called, so long as one of the listener functions calls the method, the other listener functions are no longer executed.  Reference Links:http://javascript.ruanyifeng.com/dom/event.html#toc31Https://developer.mozilla.org/zh-CN/docs/Web/APIJavaScript Definitive Guide Sixth edition   

An overview of event handling in DOM and a comprehensive analysis of its principles

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.