Accessing JavaScript Methods From Outside Its Self-Invoking Function Wrapper

Let’s say you have a method you want to be globally accessible, but want a self-invoking function around it to make sure it’s jQuery $ alias safe.

In this example, the following code is in global.js:

(function( $ ) {
   function showLoader( cfg ) {
      if( cfg == 'show') {
         $( '.loader' ).show();
      } else //more code...
   }
})(jQuery);

In this example, the following code is in myPage.js:

(function($) {
   showLoader( 'show' );
})(jQuery);

You will find that myPage.js cannot access the showLoader() method even though global.js was called first in the HTML page.

The fix for this is to push the showLoader() method out to the window (global) scope:

(function( $ ) {
   window.showLoader = function( cfg ) {
      if( cfg == 'show') {
         $( '.loader' ).show();
      } else //more code...
   }
})(jQuery);

By assigning the function to the window scope it is now globally accessible. Just remember that it is now no longer protected by the closure but it still has access to the jQuery $ alias.

Advertisements