Search code examples
javascriptjqueryscopemodule-patternrevealing-module-pattern

Determining the scope of a 'Revealing Module Pattern' module with jQuery


Say I have this module and I want it to self initialize and attach to its scope. Like so:

(function( scope ) {
    var Module = (function() {
      return {
          init: function(){
              console.log('Initialized');
          }
      };
    })();
    var module = scope.Module = Module;
    module.init();
})( self );

Now, the problem is, is that self is always the window. I don't want that. I want it to be the scope of where it's been invoked and loaded by jQuery's $.getScript(), like so:

var Master = (function($) {
    return {
        init: function() { 
            var self = this;
            $.getScript("/js/libs/module.js");
        }
    }
})(jQuery)

Is there a way to crack this?


Solution

  • I don't think you can inject scope to a self-executing script called with $.getScript. Instead you have to use some kind of exports variable to store the script until the scope can be injected.

    (function( exports ) {
       exports.Module = function() {
         return {
            init: function(scope){
               console.log('Initialized', scope);
            }
         };
       };
       var module = exports.Module;
    })( exports || window.exports = {} );
    

    Then:

    var self = this; // or whatever you want the scope to be
    $.getScript("/js/libs/module.js", function(){
        exports.Module().init(self);
    });
    

    Honestly, if you are using jQuery for the module pattern like this, consider using a more comprehensive library loader such as require.js or Frame.js.