JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

13.3.2 Event-Driven JavaScript

13.3.2 Event-Driven JavaScript

The ancient JavaScript program shown in Example 13-3 is a synchronous one: it starts running when the page loads, produces some output, and then terminates. This kind of program is very uncommon today. Instead, we write programs that register event handler functions. These functions are then invoked asynchronously when the events for which they were registered occur. A web application that wants to enable keyboard shortcuts for common actions would register an event handler for key events, for example. Even noninteractive programs use events. Suppose you wanted to write a program that would analyze the structure of its document and automatically generate a table of contents for the document. No event handlers for user input events are necessary, but the program would still register an onloadevent handler so that it would know when the document had finished loading and was ready to have a table of contents generated.

Events and event handling are the subject of Chapter 17 , but this section will provide a quick overview. Events have a name, such as “click”, “change”, “load”, “mouseover”, “keypress”, or “readystatechange”, that indicates the general type of event that has occurred. Events also have a target, which is the object on which they occurred. When we speak of an event, we must specify both the event type (the name) and the target: a click event on an HTMLButtonElement object, for example, or a readystatechange event on an XMLHttpRequest object.

If we want our program to respond to an event, we write a function known as an “event handler,” “event listener,” or sometimes just a “callback.” We then register this function so that it is invoked when the event occurs. As noted earlier, this can be done using HTML attributes, but this kind of mixing of JavaScript code with HTML content is discouraged. Instead, the simplest way to register an event handler is usually to assign a JavaScript function to a property of the target object, with code like this:

window.onload = function() { ... }; document.getElementById("button1").onclick = function() { ... }; function handleResponse() { ... } request.onreadystatechange = handleResponse;

Notice that event handler properties have names that, by convention, begin with “on” and are followed by the name of the event. Also notice that there are no function invocations in any of the code above: we’re assigning functions themselves to these properties. The browser will perform the invocation when the events occur. Asynchronous programming with events often involves nested functions and it is not uncommon to end up writing code that defines functions within functions within functions.

In most browsers, for most kinds of events, event handlers are passed an object as an argument, and the properties of this object provide details about the event. The object passed to a click event, for example, would have a property that specified which mouse button was clicked. (In IE, these event details are stored in the global event object instead of being passed to the handler function.) The return value of an event handler is sometimes used to indicate whether the function has sufficiently handled the event and to prevent the browser from performing whatever default action it would otherwise take.

Events whose targets are elements in a document often propagate up the document tree in a process known as “bubbling.” If the user clicks the mouse on aelement, for example, a click event is fired on the button. If that event is not handled (and its propagation stopped) by a function registered on the button, the event bubbles up to whatever element the button is nested within, and any click event handler registered on that container element will be invoked.

If you need to register more than one event handler function for a single event, or if you want to write a module of code that can safely register event handlers even if another module has already registered a handler for the same event on the same target, you have to use another event handler registration technique. Most objects that can be event targets have a method named addEventListener(), which allows the registration of multiple listeners:

window.addEventListener("load", function() {...}, false); request.addEventListener("readystatechange", function() {...}, false);

Note that the first argument to this function is the name of the event. Although addEventListener() has been standardized for over a decade, Microsoft is only now implementing it for IE9. In IE8 and earlier, you must use a similar method, named attachEvent():

window.attachEvent("onload", function() {...});

See Chapter 17 for more on addEventListener() and attachEvent().

Client-side JavaScript programs also use other kinds of asynchronous notification that are not, technically speaking, events. If you set the onerror property of the Window object to a function, that function will be invoked when a JavaScript error (or any

13.3 Execution of JavaScript Programs | 321

uncaught exception) occurs (see §14.6 ). Also, the setTimeout() and setInterval() functions (these are methods of the Window object and therefore global functions of client-side JavaScript) trigger the invocation of a specified function after a specified amount of time. The functions passed to setTimeout() are registered differently than true event handlers, and they are usually called “callbacks” instead of “handlers,” but they are asynchronous just as event handlers are. See §14.1 for more on setTimeout() and setInterval().

Example 13-5 demonstrates setTimeout(), addEventListener(), and attachEvent() to define an onLoad() function that registers a function to be run when the document finishes loading. onLoad() is a very useful function, and we’ll use it in examples throughout the rest of this book.

Example 13-5. onLoad(): invoke a function when the document loads

// Register the function f to run when the document finishes loading. // If the document has already loaded, run it asynchronously ASAP. function onLoad(f) {

if (onLoad.loaded) // If document is already loaded

window.setTimeout(f, 0); // Queue f to be run as soon as possible

else if (window.addEventListener) // Standard event registration method

window.addEventListener("load", f, false);

else if (window.attachEvent) // IE8 and earlier use this instead

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1