Just another object-oriented approach to jQuery plugins

It has been almost a year since I have been working primarily in JavaScript. During this time I have written three jQuery plugins and loads of other scripts.This is the story of how my approach to writing jQuery plugins has evolved.

I was working on my first plugin, which was supposed to be a large (in LOC) and went through the authoring mentioned on the jQuery site. In the beginning- it was great, a few exposed methods, well organized code, private functions, everything looked pretty. Soon the code reached some 1000 lines and it started becoming messy for me. To clarify, I am basically a java developer. I accept that the coding practices will obviously differ in every language, but for me, object oriented approach to code seems much more understandable and tidier than 'functions everywhere' thing!

I began searching for object oriented approaches people take in writing jQuery plugins. There are many, but mostly at the cost of some other flexibility. Some approaches allow only one public method, claiming only one namespace is must but more control was needed in the calendar. Some allow complete public access to the options object, but additional control was needed. There were one time calculations based on options that were necessary for the required functionality. Now making the options object public won't give me that control, will it? But apart from that, I could not understand the requirement of making it fully public. Pardon me, this statement is not to question those who follow these approaches, but this is what was thought.

A better approach was needed, where all the flexibility of making it a 'functions everywhere' is retained and a little more organization is achieved in the code. So there emerged a merger. A merger that:

  • Allows multiple methods to be made available.
  • Claims only one namespace.
  • Does not make options simply public.
  • Keeps a context, maintains a state.
  • And follows every other requirement mentioned as a guideline while writing plugins by the jQuery authors.
That merger has now evolved into a simple, precise plugin template! All you need is a case-sensitive, replace-all and you are ready with a working plugin, set with the basic features ready for more, organized plugin...

Here's the code:
/**
 * Plugin comments
 */
(function($, undefined){
 var MyPlugin = function(element, options){
  
  /*
   * *************************** Variables ***************************
   */
  var defaults = {
   defaultValue : '2'
  }; //default options
  
  /*
   * *************************** Plugin Functions ***************************
   */
  
  /*
   * Initializes plugin.
   */
  function initialize(options){
   extendOptions(options);
   sl.log("Got Options- initialize: ");
   sl.log(options);
  }
  
  /*
   * Updates plugin.
   */
  function update(options){
   sl.log("Got Options- update: ");
   sl.log(options);
  }
  
  /*
   * Destroy plugin changes
   */
  function destroy(options){
   // Remove all added classes.
   // Remove all bound methods.
   
   // Remove plugin data
   element.removeData('myplugin');
  }
  
  /*
   * Updates plugin options after plugin has been initialized.
   */
  function setOptions(options){
   extendOptions(options);
  }
  
  //expose plugin functions
  this.initialize = initialize;
  this.update = update;
  this.destroy = destroy;
  this.setOptions = setOptions;
  
  /*
   * *************************** Utility Methods ***************************
   */
  /*
   * Extend the default options using the passed options.
   */
  function extendOptions(options){
   if (options) {
    $.extend(true, defaults, options);
   }
  }
 };
 
 var mP = $.myPlugin = {version: "0.01"};
 $.fn.myPlugin = function(options){
  var args = arguments; // full argument array passed to the plugin.
  
  // Available methods in plugin
  var pMethods = {
   init : function(options){
    // Get the plugin data
    if (this.data('myplugin')) return;
    // Initialize the plugin
    var myplugin = new MyPlugin(this, options);
    // Add plugin data to the element
    this.data('myplugin', myplugin);
    myplugin.initialize(options);
   },
   update : function(options){
    // Get the plugin data
    var myplugin = this.data('myplugin');
    if (!myplugin) return; // do nothing if plugin is not instantiated.

    myplugin.update(options);
   },
   destroy : function(options){
    // Get the plugin data
    var myplugin = this.data('myplugin');
    if (!myplugin) return; // do nothing if plugin is not instantiated.
    
    // destroy data and revert all plguin changes.
    myplugin.destroy(options);
   },
   setOptions : function(options){
    // Get the plugin data
    var myplugin = this.data('myplugin');
    if (!myplugin) return; // do nothing if plugin is not instantiated.
    
    // Update the plugin options
    myplugin.setOptions(options);
   }
  };
  
  // For each element, check and invoke appropriate method passing the options object
  return this.each(function(i, tElement){
   var element = $(tElement);
   
   if (pMethods[options]){
    pMethods[options].call(element, args[1]);
   } else if (typeof options === 'object' || !options){
    pMethods['init'].call(element, args[0]);
   } else {
    $.error( 'Method ' +  options + ' does not exist in jQuery.myplugin' );
   }
  });
 };
})(jQuery);

Now what you need to get going is the replace-all, this is what you replace:

MyPlugin : PluginName
myPlugin : Plugin JQuery Method Name/pluginName
myplugin : Data Name/Variable Name
mp       : pN
pMethods : pluginNameMethods
defaults : defaulsObjectName


That's it!
You are ready with a working plugin!
Oh yes, that sl there in the code is actually the SmartLogger. Read about it here.
This is a quick post and I plan to update the post with more explanation of the code, do visit again!

Let me know how you find it in the comments.

No comments:

Post a Comment

We need to talk, says one microservice to another

‘But how?’ asks the other service! Ever wondered how we communicate? One would not believe how complex and multi-step process it is. It in...