Main Page

mirrors

In the second part of the
if
statement, another feature detect is done for IE’s
attachEvent()
method.
Note that in order to work properly, you must prepend the string
“on”
in front of the event type
(remember, the
attachEvent()
method accepts the name of the event handler, not the name of the
event, as the first parameter).
The
else
clause is simply used for all browsers that are neither DOM- nor IE-compliant. There aren’t too
many browsers that fit these criteria, so chances are this branch won’t be used very much.
Of course, you can’t just add event handlers; you must also create a way to remove them. To this end,
the
EventUtil
object gets another method called
removeEventHandler()
. As you may expect, this
method accepts the same parameters as
addEventHandler()
and uses pretty much the same algorithm:
EventUtil.removeEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.removeEventListener) { //for DOM-compliant browsers
oTarget.removeEventListener(sEventType, fnHandler, false);
} else if (oTarget.detachEvent) { //for IE
oTarget.detachEvent(“on” + sEventType, fnHandler);
} else { //for all others
oTarget[“on” + sEventType] = null;
}
};
As you can see, this code mirrors the
addEventHandler()
code almost exactly, complete with corre-
sponding feature detects. The only big difference is in the final
else
statement, where the event handler
is set to
null
and doesn’t use the
fnHandler
argument at all.
These methods can be used as shown in the following example:
<html>
<head>
<title>Add/Remove Event Handlers Example</title>
<script type=”text/javascript”>
var EventUtil = new Object;
EventUtil.addEventHandler = function (oTarget, sEventType,
fnHandler) {
if (oTarget.addEventListener) {
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) {
oTarget.attachEvent(“on” + sEventType, fnHandler);
} else {
oTarget[“on” + sEventType] = fnHandler;
}
};
EventUtil.removeEventHandler = function (oTarget, sEventType,
fnHandler) {
if (oTarget.removeEventListener) {
oTarget.removeEventListener(sEventType, fnHandler, false);
} else if (oTarget.detachEvent) {
oTarget.detachEvent(“on” + sEventType, fnHandler);
} else {
oTarget[“on” + sEventType] = null;
293
All about Events
12_579088 ch09.qxd 3/28/05 11:39 AM Page 293


JavaScript EditorFree JavaScript Editor     Ajax Editor


©