JavaScript Advanced Programming: 13th Chapter

Source: Internet
Author: User

13th Chapter

I. Understanding the flow of events

The event flow describes the order in which events are received from the page.

1. Event bubbling

The event flow of IE is called event bubbling, that is, when the event starts, it is received by the most specific element and then propagated up to the less specific node. Take the following HTML page as an example:

<! DOCTYPE html>

<title>event bubling example</title>

<body>

<div id= "mydiv" >click me</div>

</body>

If you have a single <div> element in the page, the click event propagates in the following order:

①<div>

②<body>

④document

That is, the Click event occurs first on the <div> element, which is the element we clicked on. The Click event is then propagated upward along the DOM tree, which occurs at each level of the node until it is propagated to the Document object.

2. Event Capture

Another type of event flow is called event capture. The idea of event capture is that less specific nodes should receive events earlier. If the previous page is still used as an example of the event capture, clicking the <div> element triggers the Click event in the following order.

①document

③<body>

④<div>

During the event capture process, the document object receives the Click event First, and then the event moves down the DOM tree down to the actual target of the event, the <div> element.

3.DOM Event Stream

The event flow defined by the "DOM2 level event" consists of three stages: the capture phase of the event, the target stage, and the event bubbling phase.

Second, event processing procedures

1.HTML Event handlers

Each event supported by an element can be specified using an HTML attribute with the same name as the corresponding event handler.

Event handlers defined in HTML can contain specific actions to be performed, or scripts defined elsewhere on the page, as shown in the following example:

<script type = "Text/javascript" >

function ShowMessage () {

Alert ("Hello world! ”);

}

</script>

<input type = "button" value = "click Me" onclick = "showmessage ()"/>

In this example, the ShowMessage () function is called when the button is clicked. This function is defined in a separate <script> element, and of course the code can be included in an external file, and the code in the event handler has access to any code in the global scope when it executes.

There are some unique things about specifying event handlers. A function that encapsulates the value of an element's property is created first. There is a local variable event in this function, which is the event object:

<!-Output "click"--

<input type= "button" value= "click Me" onclick = "alert (event.type)" >

With the event variable, you can access the object directly, you don't have to define it yourself, and you don't have to read from the argument list of the function. Inside this function, the this value equals the target element of the event, for example:

<!-Output "Click Me"--

<input type= "button" value= "click Me" onclick= "alert (this.value)" >

Another interesting part about this dynamic creation function is the way it expands scopes. Inside this function, you can access the document and the members of the element itself, just as you would access a local variable.

2.dom0 Level Event handlers

The traditional way to specify event handlers through JavaScript is to assign a function to an event handler property.

Each element has its own event handler properties, which are usually all lowercase, such as the onclick. By setting the value of this property to a function, you can specify an event handler, as follows:

var btn = document.getElementById ("mybtn");

Btn.onclick = function () {

Alert ("Clicked");

} ;

Here, we get a reference to a button through the Document object, and then we specify the onclick event handler for it. An event handler that is specified by using the DOM0-level method is considered a method of the element. Therefore, the event handler at this time is run in the scope of the element, in other words, the This in the program refers to the current element. Take a look at an example:

var btn = document.getElementById ("mybtn");

Btn.onclick = function () {

alert (this.id); "Mybtn"

} ;

The Click button displays the ID of the element, which is obtained through this.id.

You can also specify an event handler by removing the DOM0-level method, as long as you set the value of the event handler property to NULL as follows:

Btn.onclick = null;//Delete event handler

3.dom2 Level Event handlers

The "DOM2 level event" defines two methods for handling the actions of the specified and deleted event handlers: AddEventListener () and RemoveEventListener (). Both methods are included in all DOM nodes, and they all accept 3 parameters: the name of the event to be processed, and a Boolean value as the event handler and function. The last Boolean parameter, if True, indicates that the event handler is called during the capture phase and, if false, that the event handler is called during the bubbling phase.

The main benefit of adding event handlers using the DMO2-level method is that you can add multiple event handlers. Take a look at the following example.

var btn = document.getElementById ("mybtn");

Btn.addeventlistener ("click", Function () {

alert (this.id);

},false);

Btn.addeventlistener ("click", Function () {

Alert ("Hello world!");

},false);

Event handlers added through AddEventListener () can only be removed with RemoveEventListener (), and the parameters passed in at the same time are identical to those used when adding handlers. This means that anonymous functions added through AddEventListener () will not be removed.

4.IE Event handlers

IE implements two methods similar to the one in the DOM: Attachevent () and DetachEvent (). Both methods receive the same 2 parameters: the event handler name is a good event handler function. Unlike DOM methods:

(1) The DOM0-level method event handler runs in the scope of the element to which it belongs, while the Attachevent () method runs in the global scope.

(2) the attachevent () event handlers are not executed in the order in which they were added, but are triggered in reverse order.

5. Cross-browser event handlers

The first method to be created is AddHandler (), whose responsibility is to add events, as appropriate, using DOM0-level methods, DOM2-level methods, or IE methods, respectively. This method belongs to an object named Eventutil, which accepts 3 parameters: the element to manipulate, the event name, and the event handler function.

The method corresponding to AddHandler () is RemoveHandler (), which also accepts the same parameters. The function of this method is to remove the previously added event handler-no matter how the event handler is added to the element, and if other methods are not valid, the DOM0-level method is used by default.

Third, the event object

Event objects in 1.DOM

A DOM-compatible browser will pass an event object into a handler. The event object is passed in regardless of the method that is used to specify the handler. Take a look at the following example:

var btn = document.getElementById ("mybtn");

Btn.onclick = function (event) {

Alert ("Event.type");

};

Btn.addeventlistener ("click", Function (event) {

alert (event.type);//"Click"

},false);

The two event handlers in this example will pop up a warning box showing the type of event represented by the Event.type property.

Time objects in 2.IE

Unlike accessing the event object in the DOM, there are several different ways to access the event object in IE, depending on how you specify the event handler. When you add an event handler by using the DOM0-level method, the events object exists as a property of the Window object. Take a look at the following example:

var btn = document.getElementById ("mybtn");

Btn.onclick = function () {

var event = window.event;

alert (Event.type); "Click"

};

The event object was obtained through window.event and the type of the event being triggered was detected.

3. Cross-browser event objects

Although the event objects in the DOM and IE are different, the similarities between them can still be taken out across browser scenarios. All the information and methods of the event object in IE are available in the DOM object, except that it is implemented differently. However, this correspondence makes it easy to implement the mapping between the two event models.

4. Event Type

(1) UI events, which are triggered when the user interacts with elements on the page;

(2) The focus event, which triggers when the element Gets or goes to focus;

(3) Mouse events, when the user through the mouse to perform actions on the page triggered;

(4) Roller events, when using the mouse wheel when the trigger;

(5) A text event that is triggered when text is entered in a document;

(6) Keyboard events, when the user through the keyboard to perform operations on the page triggered;

(7) Synthetic events, when input characters for IEM trigger;

(8) A change event that is triggered when the underlying DOM structure changes.

(9) Change the name event, which is triggered when the element or attribute name changes. Such events have been deprecated and no browsers have implemented them.

V. Performance and memory

1. Event delegation

The solution to the "too many event handlers" issue is the event delegate. Event delegation takes advantage of event bubbling, specifying only one event handler to manage all events of a certain type. For example, the Click event will always bubble to the document hierarchy. That is, we can specify an onclick event handler for the entire page without having to add an event handler for each element that can be clicked. Take the following HTML code as an example:

<ul id= "Mylinks" >

<li id= "Gosomewhere" >go somewhere</li>

<li id= "dosomething" >do something</li>

<li id= "Sayhi" >say hi</li>

</ul>

It contains 3 list items that perform actions after they are clicked. As a traditional practice, you need to add 3 event handlers to them as follows.

var Item1=document.getelementbyid ("Gosomewhere");

var Item2=document.getelementbyid ("DoSomething");

var Item3=document.getelementbyid ("Sayhi");

Eventutil.addhandler (item1, "click", Function (event) {

Location.href= "http://www.wrox.com";

});

Eventutil.addhandler (item2, "click", Function (event) {

Document.title= "I changed the document ' s title";

});

Eventutil.addhandler (Item3, "click", Function (event) {

Alert ("HI");

});

If in a complex Web application this is the case for all the elements that can be clicked, the result will be countless code for adding event handlers. At this point, you can use event delegation techniques to solve this problem. With event delegates, you simply add an event handler at the highest possible level in the DOM tree, as in the following example.

var List=document.getelementbyid ("Mylinks");

Eventutil.addhandler (List, "click", Function (event) {

Event=eventutil.getevent (event);

var target=eventutil.gettarget (event);

Switch (target.id) {

Case "DoSomething";

Document.title= "I changed the document ' s title";

Break

Case "Gosomewhere";

Location.href= "http://www.wrox.com";

Break

Case "Sayhi";

Alert ("HI");

Break

}

});

2. Removing event handlers

Whenever an event handler is assigned to an element, a connection is established between the running browser code and the JavaScript code that supports the page interaction. The more connections you have, the slower the page executes. As mentioned earlier, you can use event delegation techniques to limit the number of links established. In addition, removing event handlers when they are not needed is also a solution to this problem. There are "empty event handlers" in memory that are obsolete, and are the main reasons for the memory and performance problems of Web applications.

In both cases, this problem may be caused by the first case when an element with an event handler is removed from the document. The second case is when the page is unloaded.

VI. Simulation Events

Event Simulation in 1.DOM

You can use the CreateEvent () method on the Document object to create an event object. This method takes a parameter, which is a string representing the type of event to be created. At the DOM2 level, all of these strings are in the English plural and become singular in the DOM3 level.

(1) Simulating mouse events

You can simulate mouse events by creating a new mouse event object and specifying the necessary information for it. The mouse event object is created by passing the string "Mouseevents" to CreateEvent (). The returned object has a method named Initmouseevent () that specifies information about the mouse event. This method receives 15 parameters. Below, we use an example to learn how to simulate a click event on a button:

var Btn=document.getelementbyid ("Mybtn");

Creating an Event Object

var event = document.createevent ("mouseevents");

Initialize Event object

Event.initmouseevent ("click", True,true,document.defaultview,0,0,0,0,0,false,false,false,false,0,null);

Triggering events

Btn.dispatchevent (event);

(2) Simulating keyboard events

The DOM3 level specifies that a keyboard event can be created by calling CreateEvent () and passing in "KeyboardEvent". The returned event object contains a Initkeyevent () method.

Since the DOM3 class does not advocate the use of keypress events, this technique can only be used to simulate KeyDown and KeyUp events.

var Textbox=document.getelementybyid ("MyTextBox"), event;

Create an Event object in a DOM3-level manner

if (Document.implementation.hasFeature ("Keyboardevents", "3.0")) {

Event=document.createevent ("KeyboardEvent");

Initialize Event object

Event.initkeyboardevent ("KeyDown", True,true,document.defaultview, "a", 0, "shift", 0);

}

Triggering events

Textbox.dispatchevent (event);

This example simulates holding down the SHIFT key while pressing the A key.

In other browsers, you need to create a common event and then add information specific to the event object for the keyboard event. For example:

var Textbox=document.getelementbyid ("MyTextBox");

Creating an Event Object

var event=document.createevent ("Events");

Initialize Event object

Event.initeven (type,bubbles,cancelable);

Event.view=document.defaultview '

Event.altkey=false;

Event.ctrlkey=false;

Event.shiftkey=false;

Event.metakey=false;

event.keycode=65;

event.charcode=65;

Triggering events

Textbox.dispatchevent (event);

3. Simulating other events

Although mouse events and keyboard events are the most frequently simulated events in the browser, sometimes it is also necessary to simulate a change event and an HTML event. To simulate a change event, you can use CreateEvent ("mutationevents") to create a variable event object that contains the Initmutationevent () method. For example:

var event=document.createeven ("Mutationevents");

Event.initmutationevent ("domnodeinserted", True,false,somenode, "", "", "", 0);

Target.dispatchevent (event);

The above code simulates the domnodeinserted event. Other change events can be modeled in this manner, as long as the parameters are changed.

4. Customizing DOM Events

Custom events are not triggered by the DOM native, and are intended to allow developers to create their own events. To create a new definition event, you can call CreateEvent ("Customevent"). The returned object has a method named Initcustomevent ().

Event Simulation in 2.IE

Call the Document.createeventobject () method to create an event object in IE. This method does not accept parameters, and the result returns a generic event object. Then, manually add all the necessary information for this object. The final step is to invoke the FireEvent () method on the target, which takes two parameters: the name of the event handler and the object of the events. When the FireEvent () method is called, the Srcelement and type properties are automatically added for the event object, and the other properties must be added manually.

JavaScript Advanced Programming: 13th Chapter

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.