Adding a Library Class to YUI 3

The upcoming release of YUI 3 is going to change the way we develop using the YUI framework. Instead of namespacing the library behind the YAHOO object, as was done in YUI 2, in YUI 3 the library will be referenced in isolated functional contexts by calling "YUI().use". Thus developers need to modify their code to wrap everything that uses the YUI library with a "YUI().use" call.

Example 1: Calling YUI().use

YUI().use(widget, function(Y) {
	var node = Y.Node.get(#myNode);

The first n parameters of the use method are the YUI modules needed for your callback function context; these will be added to the first parameter of the callback function (in this case Y). When adding a YUI module with other modules dependencies, those other modules will also be added. The widget module for example has dependencies on the node module, so inside of the of the callback function, we use node module, even though we didnt explicitly ask for it.

So now you know how to include all the YUI modules into your project. However, now that all code exists inside of a function context, how do we share classes between files and/or parts of your code? One approach would be to attach your code to the window object, but that would be bad practice. The YUI way is to attach your own classes to the library. To do this, use the "YUI().add" method:

Example 2: Calling YUI().add

YUI().add(theNameOfMyModule, function(Y) {
	function _F(conf) {
		_F.superclass.constructor.apply(this, arguments);
	_F.NAME = "theNameOfMyModule";
	_F.prototype {
		// the meat of your class
	Y.theNameOfMyModule = _F;
}, 3.0.0b1 ,{requires:[node]});

This code snippet creates a new module theNameOfMyModule that can be called with "YUI().use". Inside of the callback function context, "Y.theNameOfMyModule" will be available for you to instantiate. The add function signature has 4 parameters: the name of the module, the callback function in which to build the module, the version number, and a configuration object. The version number is the version number of your module, not the version number of YUI 3 that it is compatible with. The configuration object should contain at least 1 requires or use value (probably both), as requires are the YUI module instances passed into the add callback, while use are the YUI module instances passed into future "YUI().use" calls. The use value can also be used to augment existing widgets. For example, the Node class is essentially node-base augmented by node-style, node-screen, and node-aria.

Example 3: Using use with YUI().add

YUI().add(node, function(Y){}, 3.0.0b1 ,{skinnable:false, use:[node-base, node-style, node-screen, node-aria]});

Hopefully, you now have the tools required to write your own YUI 3 classes. I will be endeavoring to use YUI 3 for developing future widgets.