YUI 3, Namespaces and Dynamic Loading

During my development of the YUI port of dojo.storage, there has been a lot of time to take a look under the hood of YUI version 3. It is more intuitive and easier to use than version 2.x, although it takes a while to get used to the new nomenclature. Today, we will take a look at the new namespace function use and how to self-contain your namespace, while dynamically loading additional JavaScript functionality.

With YUI 3 you need only include 1 JavaScript file to start your application, which is:

<script type="text/javascript" src="http://developer.yahoo.com/yui/3/build/yui/yui-min.js"></script>

All interactions with the YUI library are now handled by chaining the global function "YUI()". A configuration parameter can be passed to create multiple namespaces, and to modify other properties. However, by default, the first time this method is called, it will create the namespace and each subsequent call will return the originally created namespace. Additional information available at the YUI developer center

The "YUI()" method can be chained with the usage function, allowing dynamic loading of additional YUI modules. Here is how

Example 1: Using YUI().use()

YUI().use(node, event, io, animation, function(Y) {
// you can now use Y to access all YUI methods, included those added by this call

The use method utilizes the arguments variable to iterate through all parameters passed to it. Any parameter that is a string will be dynamically added to the namespace. While the last parameter can be a function, which will be called back once the additional libraries have been loaded. If the libraries were already added to the namespace, then the callback will be executed immediately. The first parameter of the callback will be a pointer to the YUI namespace, which will be extended with any new methods provided by the libraries requested.

Therefore, any place a library is needed, simply call "YUI().use()" and those library methods will be provided. Using YUI in version 3 will heavily utilize the command pattern, reducing the need for worrying about timing and availability of libraries and/or data.