jQuery Plugin Templates

There are so many jQuery plugins out there, and so many articles about writing your own jQuery plugin. This post is another one with simple examples, and some short explainations.

jQuery plugins has some pattern(not rules), and plugins should follow it to achieve maxium compatibility, in fact, almost all plugins does follow the pattern. It is describled below:

Some examples demonstrating the pattern:

// a minimum plugin structure
(function($){
  // attach plugin to jQuery.fn
  $.fn.plugin_function = function(options){
    // return jQuery object for call chaining
    return this.each(funtion(){
      // process each element
      // implement plugin functions or attach plugin instancesj
      $(this).addClass('plugin-processed');
    });
  }
})(jQuery);
// simple extend to add plugin funtions
(function($){
  $.fn.extend({
    check: function() {
      return this.each(function() {
        this.checked = true;
      });
    },
    uncheck: function() {
      return this.each(function() {
        this.checked = false;
      });
    }
  });
})(jQuery);
// a complex plugin with options
(function ($) {

  var pluginName = "plugin_name";
  var default_options = {
      option: "value"
  };

  function Plugin( element, options ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  Plugin.prototype = {
    init: function() {
    },
    yourOtherFunction: function(el, options) {
    }
  };

  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
      if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" + pluginName, new Plugin( this, options ));
      }
    });
  };

})(jQuery);


Tags: