Events are an implementation method of asynchronous programming, essentially communication between various components of the program, and the DOM supports a large number of events;
This article uses these points to analyze the basic principles of event processing in detail: event type, event target, event handler, event object, event propagation
Finally, I will introduce the Event object to you;
1. Event type: is a full lowercase string used to indicate what type of event occurred, such as 'mouseover'
Traditional event types: form events, Window events, mouse events, keyboard events, DOM events, HTML5 events, touch screen and mobile device events, etc.
2. Event target: the object that triggers the event
3. Event listener: a function that handles or responds to events. When an object triggers an event, the browser will automatically call the function registered on the object;
Register event handler (listen to events):
1. Register as HTML attributes (it will only be triggered in the bubbling phase) such as <table id="t" onclick="modifyText();">; and some event types are usually triggered directly on the browser rather than on any specific document element. These event handlers are placed on the <body> tag, but the browser will register them on the Window object, such as <body onload="alert('Hello world!')">, and these events include:
onafterprint onfocus ononline onresize onbeforeprint onhashchange
onpagehide onstorage onbeforeunload onload onpageshow onundo
onblur onmessage onpopstate onunload oneerror onoffline onredo
The value of the event as an HTML attribute is a JS code string, which is the body of the processing function and does not contain {}. Note: Try not to register events on any other HTML tags, it violates the principle of separation of HTML and JavaScript code. If the event function may click on the event object element before it is loaded, this will cause an error;
2. Register as an attribute of the DOM element (it will only be triggered in the bubble stage). At this time, the name of the event handler attribute needs to be prefixed with 'on'. This method is compatible with all browsers. The only disadvantage is that it can only register one event handler function. If the onclick attribute is defined twice, the latter definition will overwrite the previous one; for example: window.onload = function(){...};
3. In all browsers except IE8 and previous versions, the event operations (listening and triggering) of DOM are defined in the EventTarget interface. This interface is deployed for the Element node, document node and window object. In addition, the built-in objects of the browser such as XMLHttpRequest, AudioNode, AudioContext, etc. have also deployed this interface. There are three methods of this interface, addEventListener and removeEventListener are used to bind and remove listener functions, and dispatchEvent is used to trigger events;
The addEventListener(type, listener, boolean) method is used to register listener. The third parameter sets the event propagation method. Usually, the default value false is used, which means that the listening function is triggered only in the bubble stage (pupple). When set to true, it means that the listening function is triggered in the capture stage (capture); any multiple listeners can be registered for the same type event on the same object, and all listeners will be triggered in the registration order (registering duplicate listeners will be ignored by the browser);
If you want to pass parameters to the listening function, you can wrap the listening function with anonymous functions, such as elm.addEventListener('click',function(){listen('real argument')},false);
When the registered listener is a reference variable to the function, you can use removeEventLestener(type, listener, boolean) to delete the listener on the event target. The bubble events and capture 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) { /* do something here */ }; div.addEventListener('click', listener, false); div.removeEventListener('click', listener, false);The dispatchEvent(event) method manually triggers the specified event on the current node, thereby triggering the execution of the listening function. This method returns a Boolean value. As long as a listening function calls Event.preventDefault(), it returns false. Otherwise it is true. The parameter is an instance of an Event object. The parameter cannot be empty and must be a valid event object, otherwise an error will be reported.
btn.addEventListener('click', listener, false);
var e = new Event('click');
btn.dispatchEvent(e); // The click event is immediately triggered on btn, and the listener will be called immediately
The following example determines whether the event has been cancelled based on the return value of the dispatchEvent method.
var canceled = !btn.dispatchEvent(event);
if (canceled) { console.log('Event Cancel'); }
else { console.log('Event not canceled'); }}
4. IE8 and previous versions only support attachEvent (type, listener) and detachEvent(type, listener). Their usage and addEventListener are different: a. There are only two parameters; b. The parameter type must be prefixed with 'on'; c. It allows repeated registration of the same listening event and will be called; d. There is a disadvantage to using the attachEvent method, which is that the value of this will become a window object instead of the element that triggers the event;
Call order issues: 1). Handlers registered by setting object properties or HTML attributes are always called first;
2). Handlers registered with addEventListener are called in their registration order;
3). Handlers registered with attachEvent in legacy IE may be called in any order.
Return value problem:
1). The return value of the event handler is only meaningful to the handler registered through attributes. Registering the return value of the event handler by setting the object attribute or HTML attribute to false is to tell the browser not to perform the default operations related to this event. When the browser wants to jump to a new page, the onbeforeunload event of the Window object is triggered. If its return value is a string, it will appear in the query confirmation dialog box;
2).addEventListener() or attachEvent() Register the event handler. To cancel the default operation of the browser, you must call the preventDefault() method or set the returnValue property of the event object.
This points to the problem:
1). The listening function specified by the addEventListener method, the internal this object always points to the node that triggers the event;
2). This of the event handler function registered by IE8 and previous attachmentEvent methods points to the global object;
All this object written in the following way 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)">
This object in the following way 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 will be created in each loop, and the memory will be consumed more and more; since it is not kept to the reference to the anonymous function, it cannot be called 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}); }General-purpose tool functions that are compatible with older IE:
Make sure that this tool function addEvent of the event handler points to the target object of the event
function addEvent(target,type,func){ if(target.addEventListener){ target.addEventListener(type,func,false); }else{ target.attachEvent('on'+type,function(e){ //The processing function registered by attachEvent here is not bound to a reference, so it is impossible to use detachEvent to delete return func.call(target,e); }); } }General event handler (because of IE8 and previous versions, the on-property handler as the event target needs 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}4. Event propagation: It is the process by which the browser decides which object triggers its event handler.
The event flow specified in the "DOM2 level event" includes three stages: Event capture stage ==> in the target stage ==> event bubble stage. The first thing that happens is the event capture phase (propagating from the outer layer to the inner layer), which provides an opportunity for all nodes that the event passes through to intercept events. Then there is the actual target reception event (executes in registration order). The last stage is the bubbling stage (bubbling from the inner layer to the outer layer).
When container elements and nested elements, that is, when event handlers are called in the capture stage and in the bubble stage: the event executes event handlers in the order of DOM event stream, and when the event is in the target stage, the order of event calls is determined by the writing order of the binding event
If you want the event to reach a certain node and no longer propagate, there are two ways:
1. Use the event.stopPropagation() method of the event object to prevent the propagation of the current listening function;
2. Use the event.stopImmediatePropagation() method of the event object to prevent the propagation of all listening functions of the current event on its event object;
Delegation of events: Since events will propagate upwards to the parent node in the bubble stage, the listening function of the child node can be defined on the parent node, and the listening function of the parent node can handle events of multiple child elements uniformly;
5. Event object (Event): After the event occurs, an event object will be generated and passed as a parameter to the listening function. The browser natively provides an Event object, and all events are instances of this object, or inherits the Event.prototype object. The Event object itself is a constructor that can be used to generate new instances.
var ev = new Event("look", {"bubbles":true, "cancelable":false});
document.dispatchEvent(ev);
The Event constructor accepts two parameters. The first parameter is a string, indicating the name of the event; the second parameter is an object, indicating the configuration of the event object. This parameter can have the following two properties.
bubbles: Boolean value, optional, default is false, indicating whether the event object is bubbled.
cancelable: Boolean value, optional, default is false, indicating whether the event can be canceled.
Properties of Event object:
1. Related to the stage of the event:
bubbles: Read-only property, returns a boolean value, indicating whether the current event will bubble. Different functions can be called based on whether the event will bubble.
eventPhase: Returns an integer value (one of 0,1,2,3), indicating the current state of the event
<0, the event has not occurred yet.
<1, the event is currently in the capture stage, that is, it is in the process of propagation from the ancestor node to the target node. The process is from the Window object to the Document node, then to the HTMLHtmlElement node, until the parent node of the target node.
<2, the event reaches the target node, that is, the node pointed to by the target attribute.
<3, the event is in the bubble stage, that is, in the back propagation process from the target node to the ancestor node. This process is from the parent node all the way to the Window object. This stage can only occur if the bubbles attribute is true
2. Related to the default behavior of events:
cancelable: Returns a boolean value indicating 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 indicating whether the preventDefault method has been called.
3. Related to the target node of the event:
currentTarget: Returns the node bound to the listening function of the event execution.
target: Returns the node that triggered the event. In IE6-IE8, the name of this property is not a target, but a 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 information about the event. The specific meaning is related to the event type. For mouse events, it means the number of times the mouse button is pressed at a certain position. For example, for dblclick events, the value of the detail attribute is always 2.
timeStamp: Returns a millisecond timestamp, indicating the time when the event occurred. Calculation starts from PerformanceTiming.navigationStart, which means the time it takes for the user to navigate to the web page. If you want to convert this value to a Unix epoch timestamp, you need to calculate event.timeStamp + performance.timing.navigationStart
isTrusted: Returns a boolean value indicating whether the event is trustworthy. Not very useful, different browsers support is different.
Methods of Event object:
preventDefault(): Cancels the browser's default behavior for the current event. The premise for this method to take effect is that the cancelable property of the event is true. If false, calling this method has no effect.
stopPropagation(): Terminate event to propagate further during the capture, target processing or bubble stage of the propagation process. After calling this method, the handler on the node that handles the event will be called and the event will no longer be dispatched to other nodes. 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(): prevents other listening functions from being called on the same event. As long as one of the listening functions calls the method, the other listening functions will not be executed again.
Reference link:
http://javascript.ruanyifeng.com/dom/event.html#toc31
https://developer.mozilla.org/zh-CN/docs/Web/API
Authoritative JavaScript Guide 6th Edition
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.