Explain the event handling _javascript techniques in JavaScript

Source: Internet
Author: User
Tags event listener

I. Mechanism for the dissemination of events

The client JavaScript program (that is, the browser) employs an asynchronous event-driven programming model. The Web browser generates events (event) When something interesting happens to a document, browser, element, or object associated with it. If a JavaScript application focuses on a particular type of event, it can register one or more functions to invoke when such an event occurs. Of course, this style is not unique to web programming, and all applications using the graphical user interface use it.

Now that we have to explain the incident, let's start with a few basic concepts:

    ① Event Type: is a string that describes what type of event occurred. For example, "MouseMove" means that the user moves the mouse, and "KeyDown" indicates that a key on the keyboard is pressed. The event type is just a string, sometimes called an event name;

    ② Event Target (event target): is the object that occurred or is associated with. 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 handles or responds to an event, also known as an event listener (incident listener). Applications register their event handlers in a Web browser by indicating the type of event and the target of the event.

    ④ Event object: is an object that is related to a specific event and that contains details about the event. The event object is passed as a parameter to the event handler (but in IE8 and prior versions, the global variable event is the event object). The event object has the type attribute used to specify the event type and the target attribute of the specified event target (however, in IE8 and prior versions, it is srcelement rather than target). Of course, different types of events also define some other unique properties for their associated event objects. For example, the related object of a mouse event contains the coordinates of the mouse pointer, and the related object of the keyboard event contains the details of the pressed key and the secondary key.

The above four basic concepts are finished. So here's the question--if you click on a child element B of a element A on a Web page, should the event handler for child element B be executed first or the event handler registered by element A should be executed first (assuming that element a and its child element B have registered event handlers)? As a reader, have you ever thought about this problem?

This issue is related to the event propagation mechanism in the browser. I'm sure you've all heard of event bubble and event capture capturing! Yes, they are the event propagation mechanism in the browser. No picture, no truth, no map? How wide is it to:

After looking at the picture, I believe you have probably understood the event propagation mechanism in the browser: When an event occurs, it passes through the browser's top-level object window all the way down to the element that triggers the event, which is the event capture process. However, everything is not over, and events are passed from this element all the way up to the Window object, which is the event bubbling process (but in IE8 and prior versions, the event model does not define the capture process, only the bubbling process).

So, as for the above question, it depends on whether the event handler for element a registration is in the process of capturing or bubbling. So what exactly is the process of registering an event handler in a capture procedure, and how do you register an event handler in the bubbling process? That's a good thing to say. Several ways to register an event handler:

1. Set HTML tag properties as event handlers

The event handler property for the document element, whose name consists of an "on" followed by the event name, for example: OnClick, onmouseover. Of course, this form can only register event handlers for DOM elements. Instance:

<! DOCTYPE html>
 
 

Results (after mouse clicks Div3 area):

As you can see from the results:

① because the HTML inside is not case-sensitive, so here is the event handler property name uppercase, lowercase, mixed size can be, the property value is the corresponding event handler JavaScript code;

② If you write multiple onclick event processing attributes to the same element, the browser only executes the code in the first onclick, and the following is ignored;

③ This form registers the event handlers during event bubbling;

2. Set JavaScript Object properties as event handlers

You can register an event handler for an event target by setting the event handler property for it. The event handler property name consists of "on" followed by the event name, for example: OnClick, onmouseover. Instance:

<! DOCTYPE html>  

Results (after mouse clicks Div3 area):

As you can see from the results:

① because JavaScript is strictly case-sensitive, in this form, the attribute name can only be specified in lowercase;

② If you write multiple onclick event processing attributes to the same element object, the following will overwrite the previous (PS: This is to modify the value of an object property, the value of the property is uniquely determined);

③ This form is also registered event handlers during event bubbling;

3.addEventListener ()

The first two ways appear in the early days of the web, and many browsers have implementations. The AddEventListener () method is defined in the standard event model. Any object that can be the target of an event-these objects, including window objects, document objects, and all documentation elements-defines a method called AddEventListener () that allows you to register an event handler for an event target. AddEventListener () accepts three parameters: the first parameter is the event type to register the handler, its value is a string, but does not include the prefix "on"; the second parameter refers to the function that should be called when an event of the specified type occurs; The third argument is a Boolean value. It can be ignored (this parameter cannot be ignored on some older browsers), and the default value is False. In this case, the event handler is registered during an event bubbling process. When True, the event handler is registered during the event capture process. Instance:

<! DOCTYPE html>  

Results (after mouse clicks Div3 area):

As you can see from the results:

①addeventlistener () The function of the third parameter is as stated above;

② registers multiple events of the same type with the same object through the AddEventListener () method, without ignoring or overwriting them, and executes sequentially;

The relative AddEventListener () is the RemoveEventListener () method, which also has three parameters, and the first two parameters are naturally the same as AddEventListener (). The third parameter is also required to be consistent with the third parameter of the corresponding AddEventListener (), as can be omitted, and the default value is False. It represents the deletion of an event handler 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 its previous versions of browsers do not support AddEventListener () and RemoveEventListener (). Accordingly, IE defines a similar method for attachevent () and DetachEvent (). Because IE8 and its previous version browsers do not support event capture, attachevent () does not register the event handler functions in the capture process, so attachevent () and detachevent () require only two parameters: Event type and event handler function. Also, their first argument uses the event handler property name with an "on" prefix. Instance:

var div1 = document.getElementById (' Div1 ');
Div1.attachevent (' onclick ', div1bubblefun);
function Div1bubblefun () {
console.log (' div1-bubble ');
}

Accordingly, the event handler function is removed from the object using DetachEvent (). For example:

Div1.detachevent (' onclick ', div1bubblefun);

So far, we've talked about the event propagation mechanism in browsers and the various ways to register event handlers. Now let's talk about some of the problems with the event handler call!

Two. Invocation of event handlers

1. Parameters of the event handler: as mentioned earlier, the event object is usually passed as a parameter to the event handler, but the global variable event is the event object for IE8 and its previous version of the browser. Therefore, we should pay attention to compatibility issues when writing related code. Instance (adds a click event to an element with an ID of DIV1 on the page, outputting the event type and the clicked element itself on the console when clicking on the element):

<! DOCTYPE html>
 
 

2. Event handler operating environment: about the event handler's running environment, which is the point of the call context (this value) in the event handler, you can look at the following four instances.

Example one:

<! DOCTYPE html>
 
 

Result one:

As you can see from the results:

① The first method event handler, this points to the element itself;

Example two:

<! DOCTYPE html>
 
 

Result two:

As you can see from the results:

① the second method event handler this also points to the element itself;

② the second method is present, it overrides the event handler registered by the first method;

Example three:

<! DOCTYPE html>
 
 

Result three:

As you can see from the results:

① Third method event handler this also points to the element itself;

② The third method does not overwrite the first or second method registered event handlers;

Example four:

<! DOCTYPE html>
 
 

Result four:

As you can see from the results:

① Fourth method event handler this points to the Global object window;

② Fourth method also does not overwrite the first or second method registered event handlers;

3. Order of invocation of event handlers: multiple event handlers call rules as follows:

① the handlers that are registered through HTML properties and the handlers that set the object properties are always called first;

② use AddEventListener () registered handlers to be invoked in their order of registration;

③ the handlers registered with attachevent () may be invoked in any order, so the code should not rely on the order of invocation;

4. Event Cancellation:

① the browser default action for canceling events (for example, clicking a hyperlink element automatically takes place the default action for page jumps): If you register an event handler using the first two methods, you can add a browser default action that returns a value of False to cancel the event in the handler. In browsers that support AddEventListener (), you can also cancel the default action of an event by calling the event object's Preventdefault () method. As for IE8 and its previous browsers, you can cancel the default action of an event by setting the ReturnValue property of the event object to False. Reference code:

function Cancelhandler (event) {
 var event = Event | | window.event;
 if (event.preventdefault) {
 event.preventdefault ();
 }
 if (event.returnvalue) {
 event.returnvalue = false;
 }
 return false;
}

② Cancellation of event propagation: in browsers that support AddEventListener (), a stoppropagation () method of the event object can be invoked to prevent the continuation of the event from propagating, and it can work at any stage of the event propagation (capture phase, event target itself, Bubble phase), but the Stoppropagation () method is not supported in IE8 and its previous versions of browsers, and these browsers do not support the capture phase of event propagation, and accordingly, the IE event object has a cancelbubble attribute. Setting this property to True prevents the event from propagating further (that is, preventing it from bubbling). Reference code (blocks the click events that occur in the Div3 area from bubbling to Div2 and DIV1):

<! DOCTYPE html>  

The above is the full description of JavaScript event handling, of course, about event bubbling is still available, this is what we often say the event agent or event delegate, for this knowledge will be updated gradually.

Related Article

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.