Loading ...
Sorry, an error occurred while loading the content.

Single YUILoader, multiple requires - safe design pattern

Expand Messages
  • luvdub69
    The following is a useful snippet of code which solves a number of problems using the YUILoader with a modular architecture. Remember to read the notes after
    Message 1 of 1 , Feb 27, 2009
    • 0 Attachment
      The following is a useful snippet of code which solves a number of
      problems using the YUILoader with a modular architecture.

      Remember to read the notes after this as well...

      YAHOO.namespace('example');

      YAHOO.example.YUILoader = function()
      {
      YAHOO.example.YUILoader.superclass.constructor.call(this, {
      filter: 'raw',
      combine: false,
      loadOptional: true
      });

      var modules = [
      { name: 'stuff', type: 'js', fullpath:
      'http://example.org/js/stuff.js' }
      ];

      for(var index in modules) {
      this.addModule(modules[index]);
      }
      }

      YAHOO.register('example-yuiloader', YAHOO.example.YUILoader, {version:
      '1', build: '1'});

      YAHOO.extend(YAHOO.example.YUILoader, YAHOO.util.YUILoader, {
      stack: [],

      __insert: function()
      {
      if(this.stack.length > 0) {
      var req = this.stack.shift();
      console.log('Inserting ' + req.requires);
      this.require(req.requires);
      this.insert(req.config);
      }
      },

      __require: function(req)
      {
      this.stack.push(req);
      }
      });

      var loader = new YAHOO.example.YUILoader();

      loader.__require({
      requires: ['stuff', 'reset-fonts', 'base', 'menu'],
      config: {
      onSuccess: function() {
      doStuff();
      loader.__insert();
      }
      }
      });

      loader.__insert();

      The YUILoader is subclassed, and a stack variable and 2 new methods
      are added.

      __require adds requirements for a module, with a config object which
      is passed to the insert method.

      __insert shifts the next requirement from the front of the stack, adds
      the modules required and then invokes the native insert method with
      the defined config object.

      The key to this is that all of your onSuccess handlers MUST end with
      loader.__insert() (as shown above).

      This will ensure that your module requirements are met and acted on in
      the correct order.

      Good luck!
    Your message has been successfully submitted and would be delivered to recipients shortly.