↑
Main Page
ECMAScript Basics
Every function has a
caller
property that contains a pointer to the method that is calling it. For
instance, if
funcA()
calls
funcB()
,
funcB.caller
is equal to
funcA
. Assuming that an event handler
calls
EventUtil.getEvent()
, then
EventUtil.getEvent.caller
points to the event handler itself.
Remember in Chapter 2, “ECMAScript Basics,” you learned about the
arguments
property of a func-
tion. Because the
caller
property is a pointer to a
function
, you can access the
arguments
property
of the event handler. The
event
object is always the first argument in an event handler, which means
you can access
arguments[0]
in the event handler to get the
event
object:
EventUtil.getEvent = function() {
if (window.event) {
return this.formatEvent(window.event);
} else {
return EventUtil.getEvent.caller.arguments[0];
}
};
This method can now be used inside of an event handler as shown here:
oDiv.onclick = function () {
var oEvent = EventUtil.getEvent();
};
It’s best to put all the
EventUtil
code defined in the last few sections into a separate file called
eventutil.js
to make it easy to include this script in any page.
Example
This code is rewritten from an example in the Mouse Events section:
<html>
<head>
<title>Mouse Events Example</title>
<script type=”text/javascript” src=”detect.js”></script>
<script type=”text/javascript” src=”eventutil.js”></script>
<script type=”text/javascript”>
EventUtil.addEventHandler(window, “load”, function () {
var oDiv = document.getElementById(“div1”);
EventUtil.addEventHandler(oDiv, “mouseover”, handleEvent);
EventUtil.addEventHandler(oDiv, “mouseout”, handleEvent);
EventUtil.addEventHandler(oDiv, “mousedown”, handleEvent);
EventUtil.addEventHandler(oDiv, “mouseup”, handleEvent);
EventUtil.addEventHandler(oDiv, “click”, handleEvent);
EventUtil.addEventHandler(oDiv, “dblclick”, handleEvent);
});
function handleEvent() {
var oEvent = EventUtil.getEvent();
300
Chapter 9
12_579088 ch09.qxd 3/28/05 11:39 AM Page 300
Free JavaScript Editor
Ajax Editor
©
→