jQuery: plugin structure

To write efficient jQuery plugins, one must first understand how a jQuery plugin is structured. In this post I'll outline the structure of a jQuery plugin, namely Easy Slider, to help you understand how a standard jQuery plugin is internally organized.

Creating the plugin wrapper

Each jQuery plugin is directly bound to the jQuery's fn object, which is an alias for the jQuery's prototype object. By binding your plugin to this object, you actually make it available to every element in the jQuery's wrapped set. As a best practice, you should always wrap your plugin within a self-executing function related to the jQuery wrapper itself:

(function($) {

 $.fn.easySlider = function(options){

      //...
      
    };
    
})(jQuery);

This plugin works with the following HTML structure:

<div id="images">
 <ul>
   <li><img src="images/01.jpg" alt="" /></li>
   <li><img src="images/02.jpg" alt="" /></li>
   <li><img src="images/03.jpg" alt="" /></li>
   <li><img src="images/04.jpg" alt="" /></li>
   <li><img src="images/05.jpg" alt="" /></li>
 </ul>
</div>

And with the following jQuery call:

$(function() {

  $('#images').easySlider(options);

});

Default options

The options parameter is always an object literal which will be populated by the default configuration parameters of the plugin. This can be achieved by creating an object literal with all the parameters and then by extending the options empty object with the newly created object using the jQuery's $.extend/() method:

// default configuration properties
   var defaults = {
    prevId:   'prevBtn',
 prevText:   'Previous',
 nextId:   'nextBtn', 
 nextText:   'Next',
 orientation: '', //  'vertical' is optional;
 speed:    800   
   }; 
  
   var options = $.extend(defaults, options);  

Later on you can access your configuration options as any other object's properties:

$(options.prevId).click(...);

Cascading

Each jQuery plugin should always return the jQuery object itself, that is, it should return this. This is due to the fact that a plugin should not break the jQuery's chain. Further, your plugin code should always be available to all the objects which share the same CSS selector in the chain. For that reason, plugins use the following construct:

return this.each(function() { 
  // plugin code here
});

Within this construct, a reference to the element the plugin is attached to can be actually stored in $(this):

return this.each(function() {  
  obj = $(this);
});

Now obj refers to #images (as we saw earlier) or to any other element this plugin has been bound to.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.