While remaining fully backward-compatible with the event handler mechanism of old, Version 4 browsers had the first event model that turned events into first-class objects whose properti
Trang 1708 Part III ✦ Document Objects Reference
doReadRequest(reasonCode, identification[,
domain[, path[, expiration]]])
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Once the names of the desired vCard attributes are stacked in the queue (via the
addReadRequest()method), invoke the doReadRequest()method to prompt the user for the permission that your scripts need to gain access to the data The user sees a detailed dialog box that lists the vCard fields you are requesting, as well as a description about your reason for wanting the data and who you are
The first required parameter is an integer representing one of the standard descriptions as defined by the Internet Privacy Working Group Associated text is displayed in the permission request dialog box that the user sees The codes and their strings are as follows:
Code Description String
0 Used for system administration.
1 Used for research and/or product development.
2 Used for completion and support of current transaction.
3 Used to customize the content and design of a site.
4 Used to improve the content of the site, including advertisements.
5 Used for notifying visitors about updates to the site.
6 Used for contacting visitors for marketing of services or products.
7 Used for linking other collected information.
8 Used by site for other purposes.
9 Disclosed to others for customization or improvement of the content and
design of the site.
10 Disclosed to others, who may contact you, for marketing of services and/or
products.
11 Disclosed to others, who may contact you, for marketing of services and/or
products; you have the opportunity to ask a site not to do this.
12 Disclosed to others for any other purpose.
While these description strings are fixed, you do have an opportunity to include some customized information in the second parameter The parameter is intended
to enable you to identify the Web site or organization requesting the information
userProfile.doReadRequest()
Trang 2Chapter 28 ✦ The Navigator and Other Environment Objects
Standards recommendations suggest you include a URL to the site, as well In any
case, the second parameter can be any string But it is not treated like HTML, so do
not attempt to include a clickable link here
Two optional parameters enable you to specify a domain and path within that
domain for which the user permissions are to apply Both of these parameters
closely mirror their usage in cookies, but they also depend on the capability to set
an expiration date via the fifth parameter Through IE5.5, however, the expiration
date parameter is ignored Therefore, permissions expire when the user quits the
browser (just like temporary cookies do)
Example on the CD-ROM
Related Items:addReadRequest(), clearRequest(), and getAttribute()
methods
getAttribute(“attributeName”)
Returns: String.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The getAttribute()method attempts to retrieve the vCard data based on the
items queued via the addReadRequest()method A permission dialog box
pro-vides the user an opportunity to choose which of the requested items to reveal or
to deny all access to the information Only one attribute name is permitted as a
parameter to the getAttribute()method, requiring that you invoke the method
for each attribute you want to fetch
Example on the CD-ROM
Related Items:addReadRequest(), clearRequest(), and doReadRequest()
methods
On the
CD-ROM
On the
CD-ROM
userProfile.getAttribute()
Trang 4Event Objects
Prior to NN4 and IE4, user and system actions —
events — were captured predominantly by event
han-dlers defined as attributes inside HTML tags For instance,
when a user clicked a button, the clickevent triggered the
onClickevent handler in the tag That handler may invoke a
separate function or perform some inline JavaScript script
Even so, the events themselves were rather dumb: Either an
event occurred or it didn’t Where an event occurred (that is,
the screen coordinates of the pointer at the moment the
mouse button was clicked) and other pertinent event tidbits
(for example, whether a keyboard modifier key was pressed at
the same time) were not part of the equation Until the
Version 4 browsers, that is
While remaining fully backward-compatible with the event
handler mechanism of old, Version 4 browsers had the first
event model that turned events into first-class objects whose
properties automatically carry a lot of relevant information
about the event when it occurs These properties are fully
exposed to scripts, allowing pages to respond more
intelli-gently about what the user does with the page and its
elements
Another new aspect of Version 4 event models was the
notion of “event propagation.” It was possible to have an
event processed by an object higher up the element
contain-ment hierarchy whenever it made sense to have multiple
objects share one event handler That the event being
pro-cessed carried along with it information about the intended
target, plus other golden information nuggets, made it
possi-ble for event handler functions to be smart about processing
the event without requiring an event handler call to pass all
kinds of target-specific information
Unfortunately, the joy of this newly found power is
tem-pered by the forces of object model incompatibility No fewer
than three event object models are in use today: The one
initi-ated by NN4 (whose importance diminishes with each passing
day as users migrate to other, newer browsers); the IE4+
model; and the model adopted by the W3C DOM Level 2 as
implemented in NN6+ Many of these distinctions are
addressed in the overviews of the object models in Chapter
15 In this chapter, you find out more about the actual event
objects that contain all the “goodies.” Where possible,
cross-browser concerns are addressed
29C H A P T E R
In This Chapter
The “life” of an event object
Event support in different browser generations
Retrieving information from an event
Trang 5712 Part III ✦ Document Objects Reference
Why “Events”?
Graphical user interfaces are more difficult to program than the “old-fashioned” command-line interface With a command-line or menu-driven system, users were intentionally restricted in the types of actions they could take at any given moment The world was very modal, primarily as a convenience to programmers who led users through rigid program structures
That all changed in a graphical user interface, such as Windows, MacOS, X Window System, and all others derived from the pioneering work of the Xerox Star system The challenge for programmers is that a good user interface in this realm must make it possible for users to perform all kinds of actions at any given moment: roll the mouse, click a button, type a key, select text, choose a pull-down menu item, and so on To accommodate this, a program (or, better yet, the operating sys-tem) must be on the lookout for any possible activity coming from all input ports, whether it be the mouse, keyboard, or network connection
A common methodology to accomplish this at the operating system level is to look for any kind of event, whether it comes from user action or some machine-gen-erated activity The operating system or program then looks up how it should pro-cess each kind of event Such events, however, must have some smarts about them
so that the program knows what and where on the screen the event is
What an event knows (and when it knows it)
Although the way to reference an event object varies a bit among the three event models, the one concept they all share is that an event object is created the instant the event action occurs For instance, if you click a button, an event object is cre-ated in the browser’s memory As the object is crecre-ated, the browser assigns values
to its properties — properties that reflect numerous characteristics of that specific event For a clickevent, that information includes the coordinates of the click and which mouse button was used to generate the event To be even more helpful, the browser does some quick calculations to determine that the coordinates of the
clickevent coincide with the rectangular space of a button element on the screen Therefore, the event object has as one of its properties a reference to the “screen thing” that you clicked on
Most event object properties (all of them in some event models) are read-only, because an event object is like a snapshot of an event action If the event model were to allow modification of event properties, performing both potentially useful and potentially unfriendly actions would be possible For example, how frustrating would it be to a user to attempt to type into a text box only to have a keystroke modified between the actual key press and then have a totally different character appear in the text box? On the other hand, perhaps it may be useful in some situa-tions to make sure that anything typed into a text box is converted to uppercase characters, no matter what is typed Each event model brings its own philosophy to the table in this regard For example, the IE4+ event model allows keyboard charac-ter events to be modified by script; the NN4 and W3C DOM event models do not Perhaps the most important aspect of an event object to keep in mind is that it exists only as long as scripts process the event An event can trigger an event han-dler — usually a function That function, of course, can invoke other functions As long as statements are still executing in response to the event handler, the event
Trang 6Chapter 29 ✦ Event Objects
object and all its properties are still “alive” and available to your scripts But after
the last script statement runs, the event object reverts to an empty object
The reason an event object has such a brief life is that there can be only one
event object at a time In other words, no matter how complex your event handler
functions are, they are executed serially (for experienced programmers: there is
one execution thread) The operating system buffers events that start to bunch up
on each other Except in rare cases in which the buffer gets full and events are not
recorded, event handlers are executed in the order in which the events occur
The static Event object
Up to this point, the discussion has been about the event object (with a
lower-case “e”), which is one instance of an event, with all the properties associated with
that specific event action In the NN4 and W3C DOM event models, there is also a
static Eventobject (with an uppercase “E”) In the W3C DOM event model are
addi-tional subcategories of the Eventobject These subcategories are all covered later
in this chapter, but they are introduced here to draw the contrast between the
event and Eventobjects The former, as you’ve seen, is a transient object with
details about a specific event action; the latter serves primarily as a holder of
event-related constant values that scripts can use The static Eventobject is
always available to scripts inside any window or frame If you want to see a list of
all Eventobject properties in NN4 and NN6+, use The Evaluator (Chapter 13): enter
Eventinto the bottom text box (also check out the KeyEventobject in NN6+)
The static Eventobject also turns out to be the object from which event objects
are cloned Thus, the static Eventobject has a number of properties and methods
that apply to (are inherited by) the event objects created by event actions These
relationships are more important in the W3C DOM event model, which builds upon
the DOM’s object-oriented tendencies to implement the event model
Event Propagation
Prior to the Version 4 browsers, an event fired on an object If an event handler
was defined for that event and that object, the handler executed; if there was no
event handler, the event just disappeared into the ether Newer browsers, however,
send events on a longer ride, causing them to propagate through the document
object models As you know by now, three propagation models exist, one for each
of the event models in use today: NN4, IE4+, and W3C DOM as implemented in
NN6+ Conceptually, the NN4 and IE4+ propagation models are diametrically
oppo-site each other But the W3C DOM model manages to implement both models
simul-taneously, albeit with all new syntax so as not to step on the older models
At the root of all three models is the notion that every event has a target For
user-initiated actions, this is fairly obvious If you click a button or type in a text
box, that button is the target of your mouse-related event; the text box is the target
of your keyboard event System-generated events are not so obvious, such as the
onLoadevent after a page finishes loading In all event models, this event fires on
the windowobject What distinguishes the event propagation models is how an
event reaches its target, and what, if anything, happens to the event after it finishes
executing the event handler associated with the target
Trang 7714 Part III ✦ Document Objects Reference
NN4 event propagation
Although the installed base of NN4 continues to diminish, its propagation model initiated some concepts that are found in the modern W3C DOM event propagation
model The name for the model is event capture.
In NN4, all events propagate from the top of the document object hierarchy (starting with the windowobject) downward to the target object For example, if you click a button in a form, the click event passes through the windowand docu-ment(and, if available, layer) objects before reaching the button (the form object is not part of the propagation path) This propagation happens instantaneously, so that there is no performance penalty by this extra journey
The event that passes through the window, document, and layer objects is a fully formed event object, complete with all properties relevant to that event action Therefore, if the event were processed at the window level, one of the event object’s properties is a reference to the target object, so that the event handler scripts at the window level can find out information, such as the name of the button and even get a reference to its enclosing form
By default, event capture is turned off To instruct the window, document, or layer object levels to process that passing click object requires turning on event capture for the window, document, and/or layer object
Enabling NN4 event capture
All three objects just mentioned —window, document, and layer—have a
captureEvents()method You use this method to enable event capture at any of those object levels The method requires one or more parameters, which are the event types (as supplied by Eventobject constants) that the object should cap-ture, while letting all others pass untouched For example, if you want the window
object to capture all keyPressevents, you include the following statement in a script that executes as the page loads:
window.captureEvents(Event.KEYPRESS)
Defining event handlers in the intended targets is also a good idea, even if they are empty (for example, onKeyPress=””) to help NN4 generate the event in the first place If you want the window to capture multiple event types, string the event type constants together, separated by the pipe character:
window.captureEvents(Event.KEYPRESS | Event.CLICK)
Now you must assign an action to the event at the window’s level for each event type More than likely, you have defined functions to execute for the event Assign a function reference to the event handler by setting the handler property of the win-dowobject:
window.onKeyPress = processKeyEvent window.onClick = processClickEvent
Hereafter, if a user clicks a button or types into a field inside that window, the events are processed by their respective window-level event handler functions
Turning off event capture
As soon as you enable event capture for a particular event type in a document, that capture remains in effect until the page unloads or you specifically disable the capture You can turn off event capture for each event via the window, document, or layer releaseEvents()method The releaseEvents()method takes the same
Trang 8Chapter 29 ✦ Event Objects
kind of parameters —Eventobject type constants — as the captureEvents()
method
The act of releasing an event type simply means that events go directly to their
intended targets without stopping elsewhere for processing, even if an event
han-dler for the higher-level object is still defined And because you can release
individ-ual event types based on parameters set for the releaseEvents()method, other
events being captured are not affected by the release of others
To demonstrate not only the captureEvents()and releaseEvents() methods,
but other event model techniques, I present a series of several versions of the same
document Each successive version implements an added feature to help you
expe-rience the numerous interactions among events and event handling methods The
document merely contains a few buttons, plus some switches to enable and disable
various methods being demonstrated in the section A layer object is also thrown
into the mixture because a lot of impetus for capturing and modifying event
han-dling comes from application of layers in a document
Listing 29-1 is the first example, which shows the basic event capture and release
from the outermost document level A checkbox lets you enable or disable the
doc-ument-level capture of clickevents (all checkboxes in these examples use
onMouseUpevent handlers to avoid getting in the way of tracing clickevents)
Because all clickevents are being captured by the outermost document, even
clicks to the layer’s buttons get trapped by the outermost document when
captureEvents()is set
Listing 29-1: NN4 Event Capture and Release
<HTML>
<HEAD>
<SCRIPT LANGUAGE=”JavaScript”>
function setDocCapture(enable) {
if (!enable) {
document.captureEvents(Event.CLICK)
} else {
document.releaseEvents(Event.CLICK)
}
}
function doMainClick(e) {
if (e.target.type == “button”) {
alert(“Captured in top document”)
}
}
document.captureEvents(Event.CLICK)
document.onclick=doMainClick
</SCRIPT>
</HEAD>
<BODY>
<B>Basic document-level capture of Event.CLICK</B>
<HR>
<FORM>
<INPUT TYPE=”checkbox” onMouseDown=”setDocCapture(this.checked)” CHECKED>Enable
Document Capture
<HR>
Continued
Trang 9716 Part III ✦ Document Objects Reference
Listing 29-1 (continued)
<INPUT TYPE=”button” VALUE=”Button ‘main1’” NAME=”main1”
onClick=”alert(‘Event finally reached Button:’ + this.name)”>
</FORM>
<LAYER ID=”layer1” LEFT=200 TOP=150 BGCOLOR=”coral”>
<HEAD>
</HEAD>
<BODY>
<FORM>
<BR><P><INPUT TYPE=”button” VALUE=”Button ‘layerButton1’”
NAME=”layerButton1”
onClick=”alert(‘Event finally reached Button:’ + this.name)”></P>
<P><INPUT TYPE=”button” VALUE=”Button ‘layerButton2’”
NAME=”layerButton2”
onClick=”alert(‘Event finally reached Button:’ + this.name)”></P>
</FORM>
</BODY>
</LAYER>
</BODY>
</HTML>
With document-level event capture turned on (the default), all clickevents are trapped by the document’s onclickevent handler property, a function that alerts the user that the event was captured by the top document Because all click
events for buttons are trapped there, even clickevents of the layer’s buttons are trapped at the top But if you turn off event capture, the events reach their intended targets
If the logic of the setDocCapture() function seems backwards to you, recall that when the onMouseDown event fires on the checkbox, its state is the opposite
of what it is being changed to
In Listing 29-2, I add some code (shown in boldface) that lets the layer object capture clickevents whenever the outer document event capture is turned off Inside the <LAYER>tag, a script sets the layer to capture clickevents Therefore, if you disable the outer document capture, the clickevent goes straight to the
main1button and to the layer event capture Event capture in the layer object pre-vents the epre-vents from ever reaching the buttons in the layer, unless you disable event capture for both the document and the layer
Listing 29-2: Document and Layer Event Capture and Release
<HTML>
<HEAD>
<SCRIPT LANGUAGE=”JavaScript”>
Note
Trang 10Chapter 29 ✦ Event Objects
function setDocCapture(enable) {
if (!enable) {
document.captureEvents(Event.CLICK)
} else {
document.releaseEvents(Event.CLICK)
}
}
function setLayerCapture(enable) {
if (!enable) {
document.layer1.captureEvents(Event.CLICK)
} else {
document.layer1.releaseEvents(Event.CLICK)
}
}
function doMainClick(e) {
if (e.target.type == “button”) {
alert(“Captured in top document”)
}
}
document.captureEvents(Event.CLICK)
document.onclick=doMainClick
</SCRIPT>
</HEAD>
<BODY>
<B>Document-level and/or Layer-level capture of Event.CLICK</B>
<HR>
<FORM>
<INPUT TYPE=”checkbox” onMouseDown=”setDocCapture(this.checked)” CHECKED>Enable
Document Capture
<INPUT TYPE=”checkbox” onMouseDown=”setLayerCapture(this.checked)”
CHECKED>Enable Layer Capture
<HR>
<INPUT TYPE=”button” VALUE=”Button ‘main1’” NAME=”main1”
onClick=”alert(‘Event finally reached Button:’ + this.name)”>
</FORM>
<LAYER ID=”layer1” LEFT=200 TOP=150 BGCOLOR=”coral”>
<HEAD>
<SCRIPT LANGUAGE=”JavaScript”>
function doLayerClick(e) {
if (e.target.type == “button”) {
alert(“Captured in layer1”)
}
}
layer1.captureEvents(Event.CLICK)
layer1.onclick=doLayerClick
</SCRIPT>
</HEAD>
<BODY>
<FORM>
layer1<BR><P><INPUT TYPE=”button” VALUE=”Button ‘layerButton1’”
NAME=”layerButton1”
onClick=”alert(‘Event finally reached Button:’ + this.name)”></P>
<P><INPUT TYPE=”button” VALUE=”Button ‘layerButton2’”
Continued