April 30, 2012

jQuery Plugin Template

I wanted to share a jQuery plugin template that I use. There are a lot of templates out there but I found this one fairly straight forward to use and provided all the necessary functionality.

What I really needed was a plugin that would provide some helper functions on it. I’ve seen a lot of plugins that did something to the html and attached events but I rarely found any that had public functions done in a way that made sense to me. After doing some Googling, I found something I liked and tweaked it a bit.

(function($){

    var methods = {

        init: function(options){
            return this.each(function() {
               //init each element here
            });
        },

        sampleFunction : function(){

        }

    };

    $.fn.pluginName = function(method){

        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");
        }

    }

})(jQuery);

Thats it! It’ll let me do things like this:

$('div').pluginName(); //init code
$('div').pluginName({foo:'bar'}); //init with options
$('div').pluginName('sampleFunction'); //function