jQuery Plugin Boilerplate

 
You may also like the previous version of the jQuery Plugin Boilerplate.
 

A boilerplate for jump-starting jQuery plugins development.

Contains lots of comments to help you get going easily. It is truly object-oriented, it implements public and private methods as well as public and private properties, making it the ideal candidate for when building both simple and complex jQuery plugins.

It does not adhere to the suggestions made by the jQuery documentation regarding Plugins/Authoring and by doing so it provides better performance and memory usage by not creating multiple instances of itself and attaching them to the target DOM elements.

If you still need the previous version, get it here.

With comments:

// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 2.0, July 8th, 2011
// by Stefan Gabos

// remember to change every instance of "pluginName" to the name of your plugin!
// the semicolon at the beginning is there on purpose in order to protect the integrity 
// of your scripts when mixed with incomplete objects, arrays, etc.
;(function($) {

    // we need attach the plugin to jQuery's namespace or otherwise it would not be
    // available outside this function's scope
    // "el" should be a jQuery object or a collection of jQuery objects as returned by
    // jQuery's selector engine
    $.pluginName = function(el, options) {

        // plugin's default options
        // this is private property and is accessible only from inside the plugin
        var defaults = {

            propertyName: 'value',

            // if your plugin is event-driven, you may provide callback capabilities 
            // for its events. call these functions before or after events of your 
            // plugin, so that users may "hook" custom functions to those particular 
            // events without altering the plugin's code
            onSomeEvent: function() {}

        }

        // to avoid confusions, use "plugin" to reference the
        // current instance of the  object
        var plugin = this;

        // this will hold the merged default, and user-provided options
        // plugin's properties will be accessible like:
        // plugin.settings.propertyName from inside the plugin or
        // myplugin.settings.propertyName from outside the plugin
        // where "myplugin" is an instance of the plugin
        plugin.settings = {}

        // the "constructor" method that gets called when the object is created
        // this is a private method, it can be called only from inside the plugin
        var init = function() {

            // the plugin's final properties are the merged default and 
            // user-provided options (if any)
            plugin.settings = $.extend({}, defaults, options);

            // make the collection of target elements available throughout the plugin
            // by making it a public property
            plugin.el = el;

            // code goes here

        }

        // public methods
        // these methods can be called like:
        // plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
        // myplugin.publicMethod(arg1, arg2, ... argn) from outside the plugin
        // where "myplugin" is an instance of the plugin

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

            // code goes here

        }

        // private methods
        // these methods can be called only from inside the plugin like:
        // methodName(arg1, arg2, ... argn)

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

            // code goes here

        }

        // call the "constructor" method
        init();

    }

})(jQuery);

Without comments:

// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 2.0, July 8th, 2011
// by Stefan Gabos

;(function($) {

    $.pluginName = function(el, options) {

        var defaults = {
            propertyName: 'value',
            onSomeEvent: function() {}
        }

        var plugin = this;

        plugin.settings = {}

        var init = function() {
            plugin.settings = $.extend({}, defaults, options);
            plugin.el = el;
            // code goes here
        }

        plugin.foo_public_method = function() {
            // code goes here
        }

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

        init();

    }

})(jQuery);

Usage

$(document).ready(function() {

    // create a new instance of the plugin
    var myplugin = new $.pluginName($('#element'));

    // call a public method
    myplugin.foo_public_method();

    // get the value of a public property
    myplugin.settings.property;

});

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

25 responses to “jQuery Plugin Boilerplate”

Follow the comments via RSS
  • philip, 2011-07-14, 02:16

    I really found your previous version of this boilerplate useful — just wondering if in this newer version you are suppose to instantiate a plug-in like in your example:

    // create a new instance of the plugin
    var myplugin = new pluginName($(‘#element’));

    or if you need to include a dollar sign before the plug-in name?

    Reply
    • Stefan Gabos, 2011-07-14, 05:57

      you need to dollar sign before the plugin’s name – i accidentally left it out in the examples. it’s fixed now thanks for telling me.

      the other version it’s still perfectly functional and maybe appeals to more users than this one. this is way off the jQuery way but it’s *exactly* what I was looking for. I didn’t like it in the first place that jQuery “changes the way you write JavaScript” :) With this version, it’s back to the roots :)

  • Matt, 2011-07-28, 21:08

    Very nice clean and functional design. Thank you for sharing! Question: is it possible to call the plugin with a list of parameters (as is typical with plugins) or is it more OOP such that the plugin is instantiated and then properties set e.g.

    var myplugin = new pluginName($(‘#element’));
    myplugin.settings.propertyName = ‘actual value’;
    myplugin.settings.propertyName2 = ‘actual value’;
    etc.

    Reply
    • Stefan Gabos, 2011-07-29, 06:11

      if you look in the code you’ll see that it is possible to call the plugin with a list of parameters like

      var plugin = new pluginName('$(selector)', { 
          property1: 'value 1', 
          property2: 'value 2'
      });
  • Panos Spiliotis, 2011-08-13, 17:17

    Great idea. How do you suggest one retains the chainability of the plugin?
    Thanks

    Reply
    • Stefan Gabos, 2011-08-14, 21:12

      chaining is not possible when building plugins with this…

  • Davey IJzermans, 2011-09-24, 15:22

    First of all thank you very much for this template. It really helped me understand a lot about the anatomy of a jQuery plugin.

    Using this boilerplate however, I cannot access the settings object from outside the plugin as you described. I simply get an undefined error. Any idea why?

    Davey

    Reply
    • Stefan Gabos, 2011-09-24, 15:38

      you must be doing something wrong. can you email me your code?

    • Davey IJzermans, 2011-09-24, 16:47

      I’ve refactored my code myself in the form of
      $.baseName = { var1 : 'value', functionOne() {}, functionTwo(), };

      I think i have confused the semantics of a plugin and just plain old objects for this particular piece of code.

      Your template certainly helped me kickstart my jQuery building. I bookmarked your website for future jQuery Plugin goodness and reference. Thanks again!

  • Riccardo Caroli, 2011-12-28, 10:08

    Thanks for the code..
    I’m about to rebuild a jquery plugin with classes and I have a question: what’s the point of building jquery classes if you don’t have chainability? Isn’t it better to use standard javascript classes or object literals? thanks

    Reply
    • Stefan Gabos, 2011-12-29, 07:54

      actually, all the code in the jQuery boilerplate is “standard” JavaScript that happens to have access to the $ (jQuery) object which is passed as argument at the very top. Still, you can have *some* chainability by returning a reference to an element from the class’ methods.

  • Peter Gledhill, 2011-12-31, 17:50

    I like this template very much. Just 1 question regarding the scoping of ‘this’.

    I can use methods.foo_public_method() to call a method from within the ‘init’ function.

    However the scope of ‘this’ will now refer to the ‘method’ object rather than the DOM element. So I can not return ‘this’ (to enable chaining) or access this.plugin.settings.

    Can you suggest any way of avoiding this problem?

    Cheers

    Reply
  • P.J., 2012-01-17, 07:31

    Thanks for sharing this. I need to write a jQuery plugin for a site that is also running MooTools. I understand this is not ideal but that’s the situation.

    For compatibility, can I simply replace all instances of ‘$’ in your example with ‘jQuery’?

    Thanks!

    Reply
    • Stefan Gabos, 2012-01-17, 07:55

      just use $.noConflict() after loading jQuery but before running any jQuery code, and that should take care of everything

      read more at http://api.jquery.com/jQuery.noConflict/

  • P.J., 2012-01-19, 21:39

    Great thanks! Now for another question:

    I’m using your boilerplate template for a plugin that will accept several options and do a lot of editing on different dom elements, Ajax calls, etc. I’ll need to pass in options, but there’s no need to pass in “el” since the plugin doesn’t need to be attached to any specific element.

    Should I just create an empty span element or something, and ignore the “el” parameter?

    Reply
    • Stefan Gabos, 2012-01-20, 08:01

      it’s common sense: just create the plugin like

      $.pluginName = function(options) {

      and remove all the references to el…

  • P.J., 2012-01-20, 01:19

    One more question, how would I trigger the object’s event hooks (set in the defaults variable)? For example, if I wanted to trigger onSomeEvent when an input’s value was changed or a button was clicked, is this the proper way to do it?

    myplugin.settings.onSomeEvent;

    Thanks!

    Reply
    • Stefan Gabos, 2012-01-20, 08:03

      yes, that’s pretty much it.
      i do it like this:

      // first make sure that there is a callback function 
      if (plugin.settings.onSomeEvent && typeof plugin.settings.onSomeEvent== 'function')
      
          // execute the callback function
          plugin.settings.onSomeEvent(arg1, arg2, ... argn);
  • Joseph, 2012-02-25, 08:46

    Thanks for this awesome template. However, I noticed that to start the plugin, you need this “messy code” to do it:

    var myplugin = new $.pluginName($(‘#element’),{options…});

    why not send the selector string:

    var myplugin = new $.pluginName(‘#element’,{options…});

    and in the plugin template, do this:

    plugin.el = $(el);

    Reply
  • John, 2012-02-28, 16:53

    What is the point of the callback methods (like onSomeEvent()) in the defaults? Why not just use public functions?

    Thanks!

    Reply
    • Stefan Gabos, 2012-03-02, 04:40

      so that developers can perform specific tasks at specific time points; like jQuery’s animate(), which executes a function when it’s done.

  • Rob, 2012-03-28, 01:43

    That’s a nice boilerplate, I would also include the ability to modify existing settings though like in this one: http://www.websanova.com/tutorials/jquery/jquery-plugin-development-boilerplate

    Reply
  • Vall, 2012-04-19, 10:06

    Hello,

    first of all, nice boilerplate. Was looking for something similar for a while now. I’m having a problem with initializing it, the line:
    var myplugin = new $.pluginName($(‘#element’));

    returns:
    TypeError: $.pluginName is not a constructor

    Any idea what I’m doing wrong? ;-)
    #element exists and myplugin variable is not defined before initialization.

    Thanks!

    Reply
  • Martijn, 2012-12-20, 16:30

    For what it’s worth, I disagree with your callback pattern. I think it is better to rely on jQuery’s own eventing system, using the on/off/trigger functions. It’s a lot richer in functionality and a lot more flexible than passing a function.

    Reply
  • Mau, 2012-12-29, 02:30

    Wish I had found this post 3 hours ago. Thanks really.

    Reply

Leave a Reply

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