Advanced event handling with Dom level 2 in dom2)

Source: Internet
Author: User
Tags event listener
So far, the event processing technology in this chapter is part of the dom0 level, and all browsers that support JavaScript support the dom0 API. dom2 defines an advanced event processing API, which is significantly different from the dom0 API (and more powerful ). although the dom2 standard does not generate an existing API, The dom0-level API is not removed. for basic event processing tasks, you will feel more free to use these simple APIs.
The dom2 event model is supported by all browsers except IE.
   17.2.1. Event Propagation)
In the dom0-level event model, the browser assigns an event to the document element of the event. if the object has an event handler, run the program. nothing happened again. the situation in dom2 is much more complicated. in the dom2 Advanced event model, when a document element (the target object called an event) triggers an event, the event handler of the target object is triggered. In addition, each ancestor element of the target object has one or two opportunities to process the event. the event propagation process consists of three phases.
First, in the capture phase (capturing phase), events start from the Document Object and run down the document tree to the target object. if the ancestor of any target object (not including the target object itself) also has some designated event capture handler programs, they will be run at this stage of event propagation (capture phase. (you will soon see how to register a normal event handler and capture the event handler .)
The next phase of event propagation occurs in the target object itself: all corresponding Event Handlers registered to the target object are run, which is similar to the event model provided by dom0.
The third stage of event propagation is the bubble stage, or the reverse order of the document level, from the target element to the Document Object ). although all events are affected by the capture phase (capturing phase) of event propagation, not all types of events are bubbling: for example, except for the defined commit event (submit) in addition to form, it does not make any sense to spread the event to the document element. on the other hand, General events such as mousedown make sense to other elements in the document, so these events bubble up along the document level, and the handler that triggers the corresponding event of the ancestor element of the target element. normally, the original input event bubbles, but the advanced semantic event does not. (The table 17-3 that appears later in this chapter is an authoritative list, which specifies which events are bubbling and which are not .)
During event propagation, each event handler can prevent further event propagation by calling the stoppropagation () method of the event object that represents the event. the event object and the stoppropagation () method will be further discussed later.
Some events will make the browser execute a default action associated with the event. for example, when you click a link (TAG), the browser's default behavior is to redirect to a hyperlink. such a default behavior can be executed only when the three phases of event propagation are completed. Any handler called during event propagation can prevent the occurrence of the default behavior, you can call the preventdefault () method of the event object.
Although this event propagation mechanism seems hard to understand, it helps you concentrate your event processing code. dom1 specifies all document elements and events (such as Mouseover events) allowed on those elements ). this means that, compared with the old dom0 event model, dom1 registers event handlers in many places. suppose you want to move the cursor over the section elements in each document (

) To trigger an event handler. Except for all section labels (

Register an onmouseover event handler. Instead, register a separate event handler for the document object, or, in the bubble stage, process these events.
There is also an important detail about event propagation. in the dom0 model, you can only register a handler for a specific type of event of a specific object. in the dom2 model, you can register any number of Event Handlers for a specific event type of a specific object. this is also applicable to the case where the processing function of the event object is called in the capture or bubble phase during event propagation.
  17.2.2. Event Handler Registration)
In the dom0 API, you can register an event by setting the attribute in HTML or setting the property of an object in JavaScript. in the dom2 model, you register the event handler by calling the addeventlistener () method of the object. (the DOM standard uses the listener term in this API, but in this article, I will continue to use the synonym for this term: handler .) this method has three parameters. the first is the registered event type. the event type is a string that contains lowercase letters. Remove the event attribute name from the HTML file "on. if you use the HTML attribute onmousedown in dom0, you use the string "mousedown" in dom2 ".
The second parameter is the listener function that should be called when a specified type of event is triggered. when your function is called, a unique parameter is input: event object. this object contains event details (for example, which mouse key is pressed) and some methods, such as stoppropagation (). later in this chapter, we will discuss the event interface and its subinterfaces in depth.
The last parameter of the addeventlistener () function is a Boolean value. if it is true, the specified event handler will capture the event in the capture phase of event propagation. if it is false, the event handler is a normal event handler, only when the event occurs directly on this object or occurs on the child object to bubble up to reach this element, the handler is called.
For example, you can use the addeventlistener () method to register a submit event for a form element as follows ):
Document. myform. addeventlistener ("Submit ",
Function (e) {return validate(e.tar get );}
False );
If you want to capture a mousedown event that occurs in a div with a specific name, you can use addeventlistener () as follows ():
VaR mydiv = Document. getelementbyid ("mydiv ");
Mydiv. addeventlistener ("mousedown", handlemousedown, true );
Note: These examples assume that you have defined functions named validate () and handlemousedown () in your JavaScript code.
The Event Listeners registered with the addeventlistener () function run in their defined scopes. They are not called in the parameter scope chain.
In dom2, you can call a method to add an event listener to an object, instead of setting HTML or Javascript attributes, you can register more than one event listener for a specific event of a specified object. if you register multiple listeners for the same event of the same object by calling the addeventlistener () function, when the event of that type on that object occurs (or bubbles up, or captured), all the processing programs are called. the Dom standard does not guarantee the order in which all listening functions of an object are called. Therefore, you should not rely on functions to be executed in the registered order (in fact, they are not executed in order at all ). note that if you register the same listener for the same element multiple times, only the first registration is valid and the rest are ignored.
Why do you want to register multiple event listening programs on the same event of the same object? This helps to modularize your software. suppose you have written a reusable JavaScript code module that uses the Mouseover event on the image to perform image rotation. now, assume that you have another module and want to use the Mouseover event to display additional information on the HTML pop-up form or tool tip. in the dom0 API, You have to merge the two pieces of code into one so that you can share the onmouseover attribute of an image object. on the other hand, in the dom2 API, every module can register the event listening program it needs, without having to worry about other modules.
Removeeventlistener () and addeventlistener () are a pair of methods. They need the same three parameters as addeventlistener (), but their function is to delete an event listening function from an object instead of adding it. it is often used to temporarily register an event listening function, and then quickly delete this function. for example, when you get a mousedown event, you want to register a temporary capture event listening function for the mousemove and mouseup events so that you can know whether the user has dragged the mouse. then, when the mouseup event occurs, the registered listener is removed. in this case, the deletion code of the event listener is as follows:
Document. removeeventlistener ("mousemove", handlemousemove, true );
Document. removeeventlistener ("mouseup", handlemouseup, true );
Both the addeventlistener () method and the removeeventlistener () method are defined in the event Target Interface (the eventtarget interface). In a web browser that supports the dom2 event model, the element and document node implement this interface and provide these event registration methods.
[*] Technically, Dom indicates that all nodes (including text nodes: text nodes) in the document implement the event object interface. then, in fact, the Web browser only supports event listener registration on element and document node, as well as window objects, this is beyond the DOM range.
  17.2.3. addeventlistener () and this keyword (addeventlistener () and the this keyword)
In the original dom0-level event model, when a function is registered to an event listener of a document element, it becomes a method of that document element. when the event listener is called, it is called as a method of this element. Within the function, this keyword references the element of the current event.
Dom2 is written in a language-independent method. It indicates that the listener (listeners) is an object rather than a simple function. javascript bound with Dom replaces the need for using JavaScript objects with JavaScript function event listeners. (the Javascript binding of the DOM makes JavaScript Functions Event Handlers instead of requiring the use of a JavaScript Object .) unfortunately, this binding relationship does not actually point out how the listener function is called or the value of this keyword.
Regardless of the standard, all known implementations call the handler registered using the addeventlistener () method, just as these handlers are the methods of the target object. that is to say, when the listener is called, this keyword references the object registered by the listener. if you prefer not to rely on this unspecified behavior, you can use the currenttarget attribute of the event object passed in to the listener. later in this chapter, you will see that the currenttarget attribute references the object registered by the event listener.
  17.2.4. register the object (objects) as the event listener (registering objects as Event Handlers)
Addeventlistener () allows you to register an event listening function. for object-oriented programming, you may prefer to define the methods of a client object as event listening programs, and then call them as the methods of that object. for Java programmers, Dom standards allow this: the event listener can implement the evnentlistener interface and has an object named handleevent. in Java, when you register an event listener, you pass in an object to addeventlistener () instead of a function. simply put, JavaScript bound to Dom APIs does not require you to implement the eventlistener interface. On the contrary, you can directly transmit a function reference to addeventlistener.
However, if you are writing an object-oriented JavaScript program and prefer to use the object as an event listener, you can use a function like the following to register:
Function registerobjecteventhandler (element, eventtype, listener, captures ){
Element. addeventlistener (eventtype,
Function (event) {listener. handleevent (event );}
Captures );
If an object defines the handleevent () method, you can use this function to register the object as an event listener. that method is called as the method of the listener object. This keyword references this listener object, rather than the document element that generates the event.
Although this is not part of the DOM standard, Firefox (and other browsers Based on Mozilla codebase) allows to directly pass the event listening object that defines the handleevent () method to the addeventlistener () method, to replace the function. for these browsers, there is no need to define a registration function as shown just now.
  17.2.5. event model and event type (event modules and event types)
As I mentioned earlier, dom2 is modular, so one implementation can support some of them and ignore other support for others. the event API (events API) is such a module. you can test whether a browser supports this module like this:
Document. Implementation. hasfeature ("Events", "2.0 ")
However, the event module only contains the APIs used for the basic event listening structure. the sub-module provides support for specific types of events. each sub-module provides support for a type of related event types and defines the event types of the incoming event listener. for example, the sub-module named mouseevents provides the types of events such as mousedown, mouseup, and click. it also defines the mouseevent interface. the object implementing that interface is passed in to the event listener for any event type supported by this module.
Table 17-2 lists each event module, its defined interfaces, and supported event types. note that dom2 does not standardize any Keyboard Events, so the keyboard event module is not listed here. however, the current browsers support Keyboard Events. Later in this chapter, you will learn more. (A few descriptions related to the mutationevents module are omitted here)
  Table 17-2. Event modules, interfaces, and types
Module name event interface event types
Htmlevents event abort, blur, change, error, focus, load, reset, resize, scroll, select, submit, unload
Mouseevents mouseevent click, mousedown, mousemove, mouseout, Mouseover, mouseup
Uievents uievent domactivate, domfocusin, domfocusout
As you can see in Table 17-2, the event types defined by the htmlevents and mouseevents modules are very similar to those defined by the dom0 event module. the uievents module defines the event type, which is similar to the focus, blur, and click events supported by HTML form elements, but more common, they can be generated by any document element that accepts focus or is activated.
As mentioned above, when an event occurs, its listener is passed into an event interface object that implements that type of event. the property of this object provides details that may be useful to the event listener. table 17-3 lists standard events again, but this time it is organized by event type rather than the event model. for each event type, this table indicates the type of event objects that are passed in to its listener, and whether the event has a default behavior that can be blocked using the preventdefault () method. for events in the htmlevents module, the fifth column in the table specifies which HTML elements can generate the event. for all other event types, column 5 specifies which attributes of the event object contain meaningful event details. note: The attributes listed in this column do not include attributes defined by the basic event interface that are meaningful to all event types.
  Table 17-3. event types
Event Type interface B C supported by/detail Properties
Abort event yes no,

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: 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.