jQuery Plugin Boilerplate

A boilerplate for jump-starting jQuery plugins development.

This version is obsolete. Please refer to the new version of the jQuery Plugin Boilerplate
 

With comments:

// jQuery Plugin Boilerplate
// A boilerplate for kick-starting jQuery plugins development
// version 1.3, May 07th, 2011
// by Stefan Gabos
// with help from Roger Padilla, Shinya, JohannC, Steven Black, Rob Lifford

// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {

    // here it goes!
    $.fn.pluginName = function(method) {

        // public methods
        // to keep the $.fn namespace uncluttered, collect all of the plugin's methods in an object literal and call
        // them by passing the string name of the method to the plugin
        //
        // public methods can be called as
        // element.pluginName('methodName', arg1, arg2, ... argn)
        // where "element" is the element the plugin is attached to, "pluginName" is the name of your plugin and
        // "methodName" is the name of a function available in the "methods" object below; arg1 ... argn are arguments
        // to be passed to the method
        //
        // or, from inside the plugin:
        // methods.methodName(arg1, arg2, ... argn)
        // where "methodName" is the name of a function available in the "methods" object below
        var methods = {

            // this the constructor method that gets called when the object is created
            init : function(options) {

                // the plugin's final properties are the merged default and user-provided properties (if any)
                // this has the advantage of not polluting the defaults, making them re-usable 
                this.pluginName.settings = $.extend({}, this.pluginName.defaults, options);

                // iterate through all the DOM elements we are attaching the plugin to
                return this.each(function() {

                    var $element = $(this), // reference to the jQuery version of the current DOM element
                        element = this;     // reference to the actual DOM element

                    // code goes here

                });

            },

            // a public method. for demonstration purposes only - remove it!
            foo_public_method: function() {

                // code goes here

            }

        }

        // private methods
        // these methods can be called only from inside the plugin
        //
        // private methods can be called as
        // helpers.methodName(arg1, arg2, ... argn)
        // where "methodName" is the name of a function available in the "helpers" object below; arg1 ... argn are
        // arguments to be passed to the method
        var helpers = {

            // a private method. for demonstration purposes only - remove it!
            foo_private_method: function() {

                // code goes here

            }

        }

        // if a method as the given argument exists
        if (methods[method]) {

            // call the respective method
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));

        // if an object is given as method OR nothing is given as argument
        } else if (typeof method === 'object' || !method) {

            // call the initialization method
            return methods.init.apply(this, arguments);

        // otherwise
        } else {

            // trigger an error
            $.error( 'Method "' +  method + '" does not exist in pluginName plugin!');

        }

    }

    // plugin's default options
    $.fn.pluginName.defaults = {

        foo: 'bar'

    }

    // this will hold the merged default and user-provided options
    // you will have access to these options like:
    // this.pluginName.settings.propertyName from inside the plugin or
    // element.pluginName.settings.propertyName from outside the plugin, where "element" is the element the
    // plugin is attached to;
    $.fn.pluginName.settings = {}

})(jQuery);

Without comments:

// jQuery Plugin Boilerplate
// A boilerplate for kick-starting jQuery plugins development
// version 1.3, May 07th, 2011
// by Stefan Gabos
// with help from Roger Padilla, Shinya, JohannC, Steven Black, Rob Lifford

(function($) {

    $.fn.pluginName = function(method) {

        var methods = {

            init : function(options) {
                this.pluginName.settings = $.extend({}, this.pluginName.defaults, options);
                return this.each(function() {
                    var $element = $(this), // reference to the jQuery version of the current DOM element
                         element = this;      // reference to the actual DOM element
                    // code goes here
                });

            },

            // a public method. for demonstration purposes only - remove it!
            foo_public_method: function() {
                // code goes here
            }

        }

        var helpers = {
            foo_private_method: function() {
                // code goes here
            }
        }

        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 in pluginName plugin!');
        }

    }

    $.fn.pluginName.defaults = {
        foo: 'bar'
    }

    $.fn.pluginName.settings = {}

})(jQuery);

Usage

$(document).ready(function() {

    // attach the plugin to an element
    $('#element').pluginName({'foo': 'bar'});

    // call a public method
    $('#element').pluginName('foo_public_method');

    // get the value of a property
    $('#element').pluginName.settings.foo;

});

Top

Requirements

jQuery 1.5.2+

It’s the only version I’ve tested the boilerplate with; it may be applicable to earlier versions, too. If you can test, please let me know. Thanks!

Top

36 responses to “jQuery Plugin Boilerplate”

Follow the comments via RSS
  • Roger padilla, 2011-05-11, 15:13

    Well, now I see the way you suggests to use the plugin do reuse the first created instance; anyway that is ugly, IMHO.

    $(document).ready(function() {

    // attach the plugin to an element
    $(‘#element’).pluginName({‘foo’: ‘bar’});

    // call a public method
    $(‘#element’).data(‘pluginName’).foo_public_method();

    // get the value of a property
    $(‘#element’).data(‘pluginName’).settings.foo;

    });

    And again, IMHO, the best skeleton for a jQuery plugin is (based on performance, usability and legibility):
    http://docs.jquery.com/Plugins/Authoring

    Reply
  • Simone, 2011-05-19, 15:54

    Hi Stefan!
    You did an amazing work!!!

    Your code is a “must have” for everyone want to develop a jQuery Plugin!

    Thank you!!!

    Bye,
    Simone.

    Reply
  • Simone, 2011-05-19, 16:02

    Well, I think you could move var methods = {}; and var helpers = {}; outside the $.fn.pluginName = function(method) {}; declaration.

    @Roger: I think that jQuery Plugin Authoring is a good template but has the problem of no consistency for settings variable.
    Another solution could be insert settings inside plugin data.

    Reply
  • srini, 2011-07-28, 14:18

    Great article.

    Reply

Leave a Reply

Your email address will not be published
You can use <strong>, <em>, <a>, <img>, <code>
Characters are not case-sensitive