Wednesday 11 February 2015

Using anonymous function as an alias to jQuery DOMReady function

Below syntax is a shorthand to jQuery.ready() function. The anonymous function passed to jQuery is only a callback function, it won't considered as a "JavaScript Module".

$(function(){
  
});

I.e. it does exactly the same thing that the below code block does, specify a function to execute when the DOM is fully loaded.

$(document).ready(function(){
  
});

But even though below code looks similar to the first syntax its is treated differently. This is called as module pattern or immediately invoking function in JavaScript

(function($) {
  
})(jQuery);

  • A module pattern or immediately invoking function executes immediately after it’s defined. It does not wait for the DOM to be ready.
  • Passing jQuery in to the parenthesis is to provide local scoping to the global variable.
  • All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
  • To allow external code to access to a variable or function we can expose it to the global ‘window’ object.
    (function(){
      var foo = 'Hello';
      var bar = 'World!'
      
      function baz(){
          return foo + ' ' + bar;
      }
    
      window.baz = baz; //Assign 'baz' to the global variable 'baz'...
    })();
    
    console.log(baz()); 
    
Modules are a pattern of implementation that use an immediately invoking function to provide scope and privacy around a “module” of related functionality.

Click here to read more about JavaScript Module Pattern.

If the anonymous function passed to the DOM ready() method has lot of code in it then you can use an object literal to organize the handles and callbacks as shown in below example.

var dom = {
 
    onReady: function() {
        $( "#btn1" ).click( dom.animate);
    },
 
    animate: function( event ) {
        $( "#yayeffects" ).toggle();
    } 
};
 
$( document ).ready( dom.onReady );

No comments:

Post a Comment