Overview of event handling in DOM and the overall interpretation of principles _javascript skills

Source: Internet
Author: User
Tags anonymous event listener numeric value

Events are the implementation of asynchronous programming, essentially communication between the components of a program, and DOM supports a large number of events;

This article through these points to the detailed analysis of the basic principles of event handling: Event Type, event target, event handler, event object, event propagation

Finally, we will introduce the event object;

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, touch screens and mobile device events

second, event target: The object that triggers the event

event handler (or Event listener): a function that handles or responds to an event listener. When an object triggers an event, the browser automatically invokes the function that is registered on the object;
Registering an event handler (Listener event):
1. Register as HTML attribute (will only be triggered in the bubbling phase) such as <table id= "T" onclick= "Modifytext ();" >; Some event types are usually triggered directly on the browser rather than on any particular document element, and they are placed on <body> tags, but browsers register them on window objects, such as <body onload= "alert (' Hello world! ') " , these events are:
Onafterprint onfocus ononline onresize onbeforeprint onhashchange
Onpagehide onstorage onbeforeunload onload onpageshow OnUndo
onblur onmessage onpopstate onunload onerror onoffline
The value of an event as an HTML property is a JS code string that is the body of the handler, excluding {}, Note: Try not to register events on any other HTML tag, which violates the principle of separating HTML from JavaScript code, If the event function may not have been loaded, click on the event object element, which can result in an error;

2. Register as a property of a DOM element (it will only be triggered in the bubbling phase), at which point the name of the event handler attribute needs to be added ' On ' prefix, which is compatible with all browsers, the only drawback is that only one event handler can be registered, and if the OnClick property is defined two times, the last definition overwrites the previous one; for example: Window.onload = function () {...};

3. In addition to IE8 and previous versions of all browsers, DOM event operations (listening and triggering) are defined in the Eventtarget interface. The element node, the document node, and the Window object are all deployed to this interface. In addition, the XMLHttpRequest, Audionode, Audiocontext and other browser built-in objects, also deployed this interface. The interface has three methods, AddEventListener and RemoveEventListener are used to bind and remove listener functions, dispatchevent to trigger events;
AddEventListener (Type,listener,boolean) method to register the listener, and the third parameter sets how the event is propagated, usually using the default value False, which indicates that the listener function is triggered only in the bubbling phase (pupple). When set to true, the listener function is triggered in the capture phase (capture), and any number of listener can be registered for the same type of event on the same object, and all listener will be triggered in the registration order (registration of 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 a registered listener is a reference variable to a function, you can delete the listener on the event target with Removeeventlestener (Type,listener,boolean). The bubbling and capturing events of the same listening event need to be deleted separately, and the two do not interfere with each other;

var div = document.getElementById (' div ');
var listener = function (event) {/
 
           * * 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 one of the listener calls Event.preventdefault (), otherwise true, the argument is an instance of an event object, the argument cannot be null, and must be a valid event object;
btn.addeventlistener (' Click ', Listener, false);
var e = new Event (' click ');
Btn.dispatchevent (e); The Click event is immediately triggered on the BTN and the listener is called immediately.

The following example determines whether the event was canceled based on the return value of the Dispatchevent method.
var 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), The difference between their usage and AddEventListener: A. There are only two parameters; B. parameter type must be prefixed with ' on '; c. It allows duplicate registration of the same listening event and is invoked D. A disadvantage of using the Attachevent method is that the value of this will become the Window object rather than the element that triggers the event;
Call order Problem: 1. Handlers that are registered by setting object properties or HTML properties are always called first;
2. Handlers registered with AddEventListener are invoked in their registration order;
3. The handlers that use attachevent registration in older versions of IE may be invoked in any order.
return value problem:

1. The return value of an event handler makes sense only for handlers that are registered through a property, by setting the return value of an object property or HTML property registered event handler to false, telling the browser not to perform the default action associated with this event. Triggers a Window object's onbeforeunload event when the browser jumps to a new page, and if its return value is a string, it appears in the Query confirmation dialog box;

2. AddEventListener () or attachevent () registers the event handler to cancel the browser's default action, you must call the Preventdefault () method or set the ReturnValue property of the event object.
This points to the issue:

1. The listener function specified by the AddEventListener method, the internal this object always points to the node that triggered the event;
2). IE8 and the previous Attachevent method register this for the event handler function to point 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 of 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, and more memory is consumed; because it is not possible to invoke RemoveEventListener because it does not hold a reference to an anonymous function, 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});
 
    

Generic compatible tool functions for older versions of IE:
Make sure that this is the tool function for the event handler's target object addevent

 function Addevent (target,type,func) { 
  if (target.addeventlistener) { 
    Target.addeventlistener (Type,func, FALSE);
 
  else{
 
    target.attachevent (' on ' +type,function (e) {  ///Here Attachevent the registered handler function is not bound to the reference and cannot be deleted
 
      with detachevent Return Func.call (target,e);}
 
    );
 
  }
 

Common event handlers (because of the IE8 and previous versions, handlers for the on-properties of the event target need window.event to obtain the event object, and the target node object that triggers the event is obtained through the Event.srcelement property)

function func (event) { 
  var event = event| | window.event; 
  var target = Event.target | | event.srcelement; 
  //...... Handler Code
 
}

Event Propagation: the process by which the browser determines which object triggers its event handler.
The event flow under "DOM2 level Event" includes three phases: the event capture phase ==> in the target phase ==> event bubbling phase. The first thing that happens is the event capture phase, which propagates from the outer layer to the inner layer, providing an opportunity to intercept events across all nodes of the event propagation. Then the actual target receives the event (performed in the registration order). The final stage is the bubbling phase (bubbling from the inner layer to the outer layers).

When container elements and nested elements, that is, when the event handler is invoked during the capture phase and in the bubbling phase: The event executes the event handler in the order of the DOM event flow, and when the event is in the target phase, the order of the event invocation determines the writing order of the bound event

If you want the event to go to a node and no longer propagate, there are two ways:

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 prevent the propagation of all listener functions on its event object by the current event;

the agent of the event (delegation): because the event propagates 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 uniformly handles the events of multiple child elements;

v. 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 events are instances of this object, or the Event.prototype object is inherited. 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 parameter is an object that represents the configuration of the event object. This parameter can have the following two properties.
Bubbles: Boolean, optional, default to False to indicate whether the event object is bubbling.
Cancelable: boolean, optional, default to False, indicating whether the event can be canceled.

Properties of the Event object:
1. Related to the stage of the event:
Bubbles: Read-only property that returns a Boolean value that indicates whether the current event is bubbling and calls a different function depending on whether the event bubbles.
Eventphase: Returns an integer value (one 0,1,2,3) indicating the current state of the event
<0, the incident did not happen at present.
<1, the event is currently in the capture phase, which is in the process of propagating 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 arrives at the target node, which is the node that the target attribute 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 phase can only occur if the Bubbles property is True

2. Related to the default behavior of the event:
Cancelable: Returns a Boolean value indicating whether the event can be canceled. If you want to cancel an event, you need to invoke 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 that the listener function that the event performs is bound to.
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 of the event object:
Type: Returns a String representing the event type
Detail: Returns a numeric value that represents some kind of information about the event. The specific meaning is related to the event type, for mouse events, the number of times the mouse button is pressed at a certain position, 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. Starting from Performancetiming.navigationstart, the time that the user navigates to the page is calculated. If you want to convert this value to the UNIX era timestamp, COMPUTE 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 takes effect if the Cancelable property of the event is true and if False, calling the method has no effect.
Stoppropagation (): Termination of events in the propagation process of capture, target processing or foaming phase further spread. When this method is invoked, the handler for the event on the node is invoked and the event is no longer assigned to another node. Note: This method cannot prevent other event handles from being invoked on the same Document node, but it can prevent the dispatch of events to other nodes
Stopimmediatepropagation (): Other listener functions that block the same event are invoked, and if one of the listener functions calls the method, the other listener functions will not be executed again.

Reference Links:
Http://javascript.ruanyifeng.com/dom/event.html
Https://developer.mozilla.org/zh-CN/docs/Web/API
JavaScript Authority Guide Sixth edition

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.