Accessing JavaScript Methods From Outside Its Self-Invoking Function Wrapper

Posted: September 5, 2012 in JavaScript

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s