Friday, July 16, 2010

How to Separate Logic using YUI 3 | Part 2

In my first segment, How to Separate Logic Using YUI3, I advocated using Y.Get as a way to load separate scripts as they were needed on the page, rather than on page load. This works well, with some minor drawbacks such as -if you need to set dependencies between the objects, you must create global YUI namespaced variables. Which may or may not be so bad depending on your code logic.

What I am going to recommend today is adding the new code as a module using YUI.add. This method has several advantages. All the objects will be loaded into the instance, however this may or may not mean you are loading extra code up front. Depending on your project, this may have little effect on things.

Create a module by:

YUI.add('newmodule', function(Y) {

Y.namespace('newmodule');

Y.newmodule.Mod1 = function() {
// expose an API
var privateVar = 'private';
return {
init: function(){}
doSomethingPublic" function(){}
}
};
}, '0.1.1' /* module version */, {
requires: ['base']
});


This sets up a new module called mymodules-mod1, this will expose Y.newmodule.Mod1 to the Y object in which it has scope and was loaded. Other YUI.use() blocks will not have access to the module. However, if you load all the modules you need for the page, each module can work together such as by being able to pass them to constructors or setter functions.

It is interesting to note that you can fire events from one YUI block, and it will be picked up by other event listeners in other YUI blocks. This is a good way to pass messages between objects, and write less piping code.