Details about javascript event processing and javascript events
I. Event propagation Mechanism
The client JavaScript Program (that is, the browser) adopts the asynchronous event-driven programming model. When something interesting happens to documents, browsers, elements, or related objects, Web browsers generate events ). If JavaScript applications focus on specific types of events, they can register one or more functions to be called when such events occur. Of course, this style is not unique to Web programming. All applications that use graphical user interfaces use it.
Since we need to explain how to handle events, let's start with several basic concepts:
① Event type ):Is a string used to indicate the type of event. For example, "mousemove" indicates that the user moves the mouse, and "keydown" indicates that a key on the keyboard is pressed. The event type is only a string, and is sometimes called the event name );
② Event target ):Is an event or related object. Window, Document, and Element objects are the most common event targets. Of course, the XMLHttpRequest object in AJAX is also an event target;
③ Event handler ):Is a function that processes or responds to events. It is also called an event listener ). Applications register their event handler functions in a Web browser by specifying the event type and event target.
④ Event object ):Is an object related to a specific event and contains detailed information about the event. The event object is passed as a parameter to the event handler (but in IE8 and earlier versions, the global variable event is the event object ). Event objects can be used to specify the type attribute of the event type and the target attribute of the event target (but in IE8 and earlier versions, use srcElement instead of target ). Of course, different types of events define some other unique attributes for their related event objects. For example, a mouse event object contains the coordinates of the mouse pointer, and a keyboard event object contains detailed information about the pressed key and the secondary key.
The above four basic concepts have been completed. The problem arises-if you click a child element B of Element a on a web page, should we first execute the event handler registered by child element B, or should we first execute the event handler registered by element a (assuming that both Element a and its child element B have an event handler registered )? Have you ever thought about this question as a reader?
This problem involves the event propagation mechanism in the browser. I believe you have heard of event bubble and event capturing! Yes, they are the event propagation mechanism in the browser. No picture, no truth, no matching picture? How can we broaden the scope:
After reading the figure, I believe you have probably understood the event propagation mechanism in the browser: when an event occurs, it will first pass down from the browser's top-level Object Window, always pass to the element that triggers this event, which is the event capture process. However, everything is not over, and the event is passed all the way from this element to the Window object, which is the event Bubbling Process (but in IE8 and earlier versions, the event model does not define the capture process, only the bubble process ).
Therefore, for the above question, we have to check whether the event handler registered by element a is in the capture or bubble process. So what is registering an event handler during the capture process and registering an event handler During the bubble process? So let's talk about several methods to register the event handler:
1. Set the HTML Tag attribute to the event handler
The event handler attribute of the document element. Its name consists of "on" followed by the event name, such as onclick and onmouseover. Of course, this form can only register Event Handlers for DOM elements. Instance:
<!DOCTYPE HTML>
Result (after clicking the div3 area ):
The result shows that:
① Because HTML is case-insensitive, the attribute name of the event handler can be big-coded, lowercase, and mixed-size. The attribute value is the JavaScript code of the corresponding event handler;
② If multiple onclick event processing attributes are written to the same element, the browser will only execute the code in the first onclick event, and the subsequent code will be ignored;
③ This form registers the event handler during event bubbling;
2. Set the JavaScript Object Property to an event handler
You can register an event handler for an event by setting the event handler attribute of the event target. The property name of the event handler consists of "on" followed by the event name, for example, onclick and onmouseover. Instance:
<!DOCTYPE HTML>
Result (after clicking the div3 area ):
The result shows that:
① JavaScript is case sensitive. Therefore, subordinate names in this form can only be in lower case;
② If multiple onclick event processing attributes are written to the same element object, the subsequent write will overwrite the previous one (ps: This is the value of modifying an object attribute, the attribute value is uniquely determined );
③ This form also registers the event handler during event bubbling;
3. addEventListener ()
The first two methods appeared at the beginning of the Web, and many browsers were implemented. The addEventListener () method is defined in the standard event model. Any object that can become the event Target-these objects include Window objects, Document objects, and all Document elements-all define a method named addEventListener, you can use this method to register an event handler for the event target. AddEventListener () accepts three parameters: the first parameter is the event type of the handler to be registered. Its value is a string, but does not include the prefix "on "; the second parameter refers to the function that should be called when a specified type of event occurs. The third parameter is a Boolean value, which can be ignored (this parameter cannot be ignored in some old browsers ), the default value is false. In this case, the event handler is registered during the event Bubbling Process. If this parameter is set to true, the event handler is registered during the event capture process. Instance:
<!DOCTYPE HTML>
Result (after clicking the div3 area ):
The result shows that:
① The Role Of The third parameter addEventListener () is as mentioned above;
② Use the addEventListener () method to register multiple events of the same type for the same object. The events will not be ignored or overwritten, but will be executed in sequence;
Compared with addEventListener (), the removeEventListener () method has three parameters. The first two parameters have the same meaning as addEventListener, the third parameter only needs to be consistent with the third parameter of the corresponding addEventListener (). It can also be omitted. The default value is false. It indicates that an event processing function is deleted from an object. Instance:
div1.addEventListener('click', div1BubbleFun, false);div1.removeEventListener('click', div1BubbleFun, false);function div1BubbleFun(){ console.log('div1-bubble');}
4. attachEvent ()
However, IE8 and earlier Browsers Do not support addEventListener () and removeEventListener (). Correspondingly, IE defines similar methods attachEvent () and detachEvent (). Because IE8 and earlier Browsers Do not support event capture, attachEvent () cannot register the event handler during the capture process. Therefore, attachEvent () and detachEvent () must have only two parameters: event Type and event processing function. In addition, their first parameter uses the property name of the event handler with the "on" prefix. Instance:
var div1 = document.getElementById('div1');div1.attachEvent('onclick', div1BubbleFun);function div1BubbleFun(){ console.log('div1-bubble');}
Correspondingly, the event handler function is deleted from the object using detachEvent (). For example:
div1.detachEvent('onclick', div1BubbleFun);
So far, we have discussed the event propagation mechanism in the browser and various methods for registering event handlers. Now let's talk about Some Problems in the event processing program calling!
Ii. Call of the event handler
1. Parameters of the event handler:As mentioned above, the event object is usually passed as a parameter to the event handler, but the global variable event in IE8 and earlier browsers is the event object. Therefore, we should pay attention to compatibility issues when writing relevant code. Instance (add a click event to the element with the id of div1 on the page. When this element is clicked, the event type and the clicked element itself are output on the console ):
<!DOCTYPE HTML>
2. Running environment of the event handler:For the running environment of the event handler, that is, the point of calling context (this value) in the event handler, see the following four instances.
Instance 1:
<!DOCTYPE HTML>
Result 1:
The result shows that:
① Method 1 this in the event handler points to the element itself;
Example 2:
<!DOCTYPE HTML>
Result 2:
The result shows that:
① Method 2 this in the event handler also points to the element itself;
② If the second method exists, it will overwrite the event handler registered in the first method;
Example 3:
<!DOCTYPE HTML>
Result 3:
The result shows that:
① Method 3 this in the event handler also points to the element itself;
② The third method does not cover the event handler registered by the first or second method;
Example 4:
<!DOCTYPE HTML>
Result 4:
The result shows that:
① Method 4 this in the event handler points to the Global Object Window;
② Neither the fourth method will cover the event handler registered by the first or second method;
3. Sequence of Event Handlers:The Calling rules of multiple event handlers are as follows:
① The Handler registered through the HTML property and the handler set the object property are always preferentially called;
② The handlers registered using addEventListener () are called in the order they are registered;
③ The Handler registered with attachEvent () may be called in any order, so the Code should not depend on the call order;
4. Event cancellation:
① Cancel the default operations of the event browser (for example, clicking a hyperlink will automatically redirect to the page): If you use the first two methods to register the event handler, you can add the return value "false" to the handler to cancel the default operations of the event browser. In a browser that supports addEventListener (), you can also call the preventDefault () method of the event object to cancel the default event operation. For IE8 and earlier browsers, you can set the returnValue attribute of the event object to false to cancel the default event operation. Reference code:
function cancelHandler(event){ var event = event || window.event; if(event.preventDefault){ event.preventDefault(); } if(event.returnValue){ event.returnValue = false; } return false;}
② Cancel event propagation: in a browser that supports addEventListener (), you can call a stopPropagation () method of the event object to prevent the event from spreading, it can work at any stage during event propagation (capture phase, event Target itself, bubble phase). However, the stopPropagation () method is not supported in IE8 and earlier browsers, in addition, these browsers do not support the capture phase of event propagation. Correspondingly, the IE event object has a cancelBubble attribute. setting this attribute to true can prevent further event propagation (that is, prevent event bubbles ). Reference Code (to prevent click events that occur in the div3 region from bubbling to div2 and div1 ):
<!DOCTYPE HTML>
The above is a full introduction to javascript event processing. Of course, there are still some available features about event bubbling, which is what we often call event proxy or event delegation, this knowledge will be updated in the future.