Friday, 24 June 2011

jQuery plugin template

(function($) {
 //Set default settings
 //These will be overridden by the values passed to the plugin
 var settings = {
  foo: false,
  bar: true
 };
 //Define public methods
 var methods = {
  init: function(options) {
   return this.each(function() {
    var $this = $(this),
     data = $this.data('pluginName');
    if(options) {
     //Override plugin settings with options passed
     $.extend(settings, options);
    };
    if(!data) {
     //If data isn't set, plugin hasn't been run before
     //so do your initial setup
     //Set any persistent data
     $this.data('pluginName', {
      runCount: 0
     });
     $this.pluginName('foobar');
    } else {
     $this.pluginName('foobar');
    }
   });
  },
  foobar: function(options) {
   return this.each(function() {
    var $this = $(this),
     data = $this.data('pluginName');
    data.runCount++;
    if(options) {
     //Override plugin settings with options passed
     $.extend(settings, options);
    };
    if(settings.foo) {
     $this.append('<div>Foo ' + data.runCount + '</div>');
    }
    if(settings.bar) {
     $this.append('<div>Bar ' + data.runCount + '</div>');
    }
   });
  }
 };
 $.fn.pluginName = function(method) {
  var $this = $(this);
  if(methods[method]) {
   return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  } else if(typeof method === 'object' || ! method) {
   return methods.init.apply(this, arguments);
  } else {
   $.error('Method ' +  method + ' does not exist on jQuery.pluginName');
  };
 };
})(jQuery);

You call this plugin like so:

jQuery('.mydiv').pluginName();

or custom settings:

jQuery('.mydiv').pluginName({foo:true,bar:false});

Once initialised you can use the public methods:

jQuery('.mydiv').pluginName('foobar', {bar:true});

No comments:

Post a Comment