Search

4/23/2008

yui-event

Handler Attachment Deferral

If you attempt to attach a handler to an element before the page is fully loaded, the Event Utility attempts to locate the element. If the element is not available, Event periodically checks for the element until the window.onload event is triggered. Handler deferral only works when attaching handlers by element id; if you attempt to attach to a DOM object reference that is not yet available, the component has no way of knowing what object you are trying to access.
Yahoo! UI Library: Event Utility - Automatic Scope Correction

Event handlers added with Internet Explorer's attachEvent method are executed in the window scope, so the special variable this in your callback references the window object. This is not very useful. Even more vexing is the fact that the event object in Internet Explorer does not provide a reliable way of identifying the element on which the event was registered; standards-based browsers supply this as the currentTarget property, but this property is not present in IE.

By default, the Event Utility automatically adjusts the execution scope so that this refers to the DOM element to which the event was attached, conforming to the behavior of addEventListener in W3C-compliant browsers. Moreover, the event subscriber can override the scope so that this refers to a custom object passed into the addListener call.

Automatic Event Object Browser Abstraction

The first parameter your callback receives when the event fires is always the actual event object. There is no need to look at window.event.

YAHOO.util.Event.getListeners lets you retrieve all of the listeners that were attached to an element via addListener. Optionally, you can retrieve all bound listeners of a given type:

// all listeners
var listeners = YAHOO.util.Event.getListeners(myelement);
for (var i=0; i<listeners.length; ++i) {
var listener = listeners[i];
alert( listener.type ); // The event type
alert( listener.fn ); // The function to execute
alert( listener.obj ); // The custom object passed into addListener
alert( listener.adjust ); // Scope correction requested, if true, listener.obj
// is the scope, if an object, that object is the scope
}

// only click listeners
var listeners = YAHOO.util.Event.getListeners(myelement, "click");

沒有留言: