Wednesday, May 28, 2008

YUI study notes - Event

The window.onload event is synchronous with images and external dependencies, so it doesn't fire until they've all resolved (or timed out), also in some browser (IE), the target elements that do not yet exist when onload event fired. What we really want is an event that fires when the DOM ready, YUI's onDOMReady(), onAvailable() and onContentReady () help to avoid this problem.

Event object is accessed differently in different browser. In IE the event object is accessed through the window object, whereas in Firefox, it is automatically passed to your event handler as an argument.

[1] has a good explanation on the callback function signature.

Callback for Native Browser Events


var callback = function(e, o) {
alert(o.msg);
};

YAHOO.util.Event.addListener(elemId, "click", callback, {msg: "hi"});

Callback for Custom Events
If the custom event is fired with parameter signature YAHOO.util.CustomEvent.LIST, which is by default

var callback = function(e, a, o) {
//a is an array contains arguments fire method: arg1, arg2, ...
//o is the object passed from the subscribe method
alert(o.msg);
};

//to fire this event
eventObj.fire(arg1, arg2, ...);

//to listen to this event
eventObj.subscribe(callback, {msg: "hi"});

where
e - Name of this custom event.
a - Arguments that passed to the fire method of this event.
o - Object that passed as a parameter to this callback function.

If the custom event is fired with parameter signature YAHOO.util.CustomEvent.FLAT

var callback = function(a, o) {
//a is the first argument that passed to fire method of this event
//o is the object passed from the subscribe method
alert(o.msg);
};

//to fire this event
eventObj.fire(arg);

//to listen to this event
eventObj.subscribe(callback, {msg: "hi"});

No comments: