Jan 5, 2010

(function($){ }) JQuery : What It Really Is?

Today I happen to use the code snippet


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


But, for around an hour, I was wondering as to what the above function really does? what is the use of wrapping functions like


$(this).submit(function(){}
$(document).ready(function(){} 


inside the above?

After a bit of research, I understood what it really does and that is awesome. This post further gives you a heads up on what


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


is in detail.

The $ in


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


can be considered to be prototype reference outside the function call. This $ becomes a jquery reference inside the function. as a result, even if this $ variable or function is being used by any other javascript library, this reference overwrites all and proves to be a nice jquery reference well within the function.

Generally you can expect to see all JQuery plug-ins to be written inside this function where $ is being passed as a parameter. Before we take a look at jQuery plug-ins, consider the code snippet below:


var userDefinedFunction = function ($) { 
  //your code here
};
userDefinedFunction (jQuery);

is equivalent to


(function ($) { 
    //your code here
})(jQuery)


Having discussed this, let me give you ahead up on writing customized plug-ins. Just follow the steps below and your customized JQuery plug-in is ready!

  1. Let us consider that we write a plugin by name sample.
  2. You have to have a file jquery.sample.js
  3. Within the file we can have methods for the plug-in. For this, you need to extend the JQuery object as follows:
  4. (function($){  
    $.fn.sample = function() {});
  5. You can now access this function using the below code in your html file:
  6. <script language="javascript" type="text/javascript">
                $('#<form name>').sample();
    </script>
    
  7. Default settings for this plug-in is created by using the code



    $.fn.sample = function(options) 
    {var defaults = {inputVal: 1, trueVal : 'true', falseVal : 'false',submitButton : '#submit'}
    var pluginOptions = $.extend(defaults, options);
    



  8. If ever you intend to call this function with new values which are different from the default values, use the following snippet and get it done!
  9. <script language="javascript" type="text/javascript">
                $('#<form name>').sample({inputVal:2, trueVal:'yes',falseVal:'no', submitButton:'#ClickMe');
    </script>
    
  10. As such, this was a nice learning and a great heads up on JQuery plug-ins!But, there are much more interesting tips to come! Stay tuned!



No comments:

Post a Comment