Thursday, February 11, 2010

How to separate logic using YUI 3

There are several things to consider when building up the javascript on a page. How the js files will be loaded, what io actions will take place, animations, form validation etc. Yahoo User Interface give you a nice set of options to put it all together, while minimizing the downloads to the client.

For our example, let's assume we have 2 separate Ajax calls we want to make, which then triggers an animation. In this case we want to break out each "part" into separate files, and only load the code the user needs. To begin we will have a "setup" .js file which will use Y.Get.script('', {onSuccess: ...}) to load the other files when needed, and will also setup some namespaces.

YUI().use("node-base", function(Y){
    UI = {
      filesLoaded: false,
      setup: function(){
          // Setup Event  - event, fnc, context, [args]
          Y.on('click', this.fireAjax1, 'btnFireAjax', this) 

      },
      fireAjax1: function(){
        if(!this.filesLoaded){
           // Load the Script 
           Y.Get.script('js/PageAjax1.js', {onSuccess: this.ajaxLoaded1);
        } else {
          this.ajaxLoaded1();
        }
      },

      ajaxLoaded1: function(){
          // Fire from namespace
          YUI.Ajax1.fire();
          this.filesLoaded = true;
      },

       fireAjax2 [...] ajaxLoaded2 [...]
    };

    // Put this object in scope
    YUI.UI = UI;

});

When using the Y.io, you want to break out each separate call into different YUI().use() blocks as you want to set a separate callback for each event. It just makes it easier to deal with instead of making a single "dispatch" function.

In the PageAjaxX.js files we can load the io and animation libraries/files as needed. This ensures that the js is only loaded when it's needed which cuts down on initial page load times and improves user experience. Your objects can then be put in a namespace and work with each other nicely.

No comments: