HTML and CSS Reference
In-Depth Information
if (tddjs.isHostMethod(document, "addEventListener")) {
_addEventHandler = function (element, event, listener) {
element.addEventListener(event, listener, false);
};
} else if (tddjs.isHostMethod(document, "attachEvent")) {
_addEventHandler = function (element, event, listener) {
element.attachEvent("on" + event, function () {
var event = normalizeEvent(window.event);
listener.call(element, event);
return event.returnValue;
});
};
} else {
return;
}
dom.addEventHandler = _addEventHandler;
}());
This implementation is not complete; for instance, the event object is not suf-
ficiently normalized. Because details are less important than the overall concept in
this example, I leave further normalization as an exercise to the reader. Note that the
event object is a host object, and so you may not be comfortable adding properties
on it. An alternative approach could be to return a regular object that maps calls to
the event object.
tddjs.dom.addEventHandler
operates as a proxy for registering event
handlers, opening the door to supporting custom events. One example of such a
custom event is the proprietary
mouseenter
event mentioned previously, only
supported by Internet Explorer. The
mouseenter
event only fires once as the
mouse enters the bounds of an element. This is more helpful than
mouseover
in
many cases, as event bubbling causes the latter to fire every time the user's mouse
enters one of the target element's descendants, not only when the mouse enters the
target element.
To allow for custom events, we can wrap the
_
addEventHandler
function
and have it first look for custom events in the
dom.customEvents
namespace.
The
mouseenter
implementation is added to this namespace only if the environ-
ment does not already support it—we don't want to override a native event with
an inferior version—and if the required
mouseover
and
mouseout
events are
supported. Listing 10.15 shows a possible implementation.