(note (code cslai))

Maintaining State with YUI Event

When one start writting Javascript in patterns like the module pattern, then sooner or later he would want to maintain the state when an event handler is called. The reason I am still using YUI to handle my event handling code is because I like how state can be maintained.

There are some other interesting things in the Event utility like YAHOO.util.Event.onDOMReady, YAHOO.util.Event.onContentReady as well as YAHOO.util.Event.onAvailable methods. Most of the time, the developer may want certain code to start running as soon as the DOM tree is loaded completely without having to wait for all the elements (image, flash etc.) to finish loading. Then YAHOO.util.Event.onDOMReady may come in handy. For example

YAHOO.util.Event.onDOMReady(function() {
alert('Good day!');
});

After loading the DOM tree, then the browser will prompt ‘Good day!’ to the user.

Back to the topic, if the developer wishes to listen to some event and perform action as soon as the event is fired, then he may register the event as follows.

YAHOO.util.Event.on(some_element, 'change', some_callback_function, extra_parameter);

Everything looks fine, but when the developer has structure his code into patterns like the module patttern as follows:


(function(Event) {
 
var Some_Module = function() {
return {
foo: 'bar',
execute: function() {
alert(this.foo);
},
 
listen: function() {
Event.on(element, 'change', this.execute, null, this);
}
};
}();
 
})(YAHOO.util.Event);

Notice in the forth and fifth arguments passed into the YAHOO.util.Event.on function, I am passing in no extra parameters and the fifth argument defines the scope of this keyword in the Some_Module.execute method.

If the developer uses YAHOO.util.Element to wrap certain elements, then he can also use another way to listen to the event

var element = YAHOO.util.Element('div');
element.on(some_event, some_callback_function, some_extra_parameter, some_scope);

Speaking of YUI Element, I just recently found a way to ’emulate’ jQuery’s $() function with YUI components.


(function($) {
$(document.body); // returns the body element wrapped in YAHOO.util.Element class
})(function(_selector) {
var result = YAHOO.util.Selector.query(_selector);
 
if(result.length > 0) {
if(result.length == 1) {
result = new YAHOO.util.Element(result[0]);
} else {
for(i in result) {
result[i] = new YAHOO.util.Element(result[i]);
}
}
} else {
result = false;
}
 
return result;
});

Although not as powerful as jQuery’s $() function, but It can be useful in many situations where YUI is the only choice.

Exit mobile version