jQuery Plugin Boilerplate



You are currently browsing comments. If you would like to return to the full story, you can read the full entry here: “jQuery Plugin Boilerplate”.

36 thoughts on “jQuery Plugin Boilerplate

  1. Steven Black

    Nice post. One suggestion.

    Stephan, for better clarity, in the English language the semantics are:

    options: values that may be provided by the user.
    defaults: provided by the plugin/function/object that may be overridden by user-specified options.
    settings: the run-time values.

    Like this:

    settings = $.extend( {}, defaults, options )

    This has the added advantage of not polluting the defaults, making the same instace re-usable with new options.

    1. Stefan Gabos Post author

      Makes sense, I updated the code. Also, previously, the “init” method could not be called manually making it impossible to reuse the same instance with new options. Thanks!

  2. Roger Padilla

    Very useful, thanks for sharing!

    I think an improvement will be to put out of the ‘pluginName’ function (just after ‘(function($) {‘) the declaration of the variables ‘options’, ‘methods’ and ‘helpers’, in this way each call to the plugin will not create its own versions of such objects but will share them across multiple invocations to the plugin.

    var aVar = $(selector);
    aVar.pluginName(‘methodName1’, arg1, … argn);
    aVar.pluginName(‘methodName2’, arg1, … argn);

  3. Ben

    Nice.

    One add-on maybe

    it’s often recommended to start with a semicolon, like so:

    ;(function($) {

    This prevent errors when minifying plugins together to increase response speed. That prevent the previous set of code from interfering with your own plugin…

    1. Stefan Gabos Post author

      that definitely doesn’t increase response speed but can’t hurt either if mixed with some poorly written code. i’ll add that, too. thanks.

    1. Stefan Gabos Post author

      indeed πŸ™‚ that’s where everybody starts, right? but there are things missing like public and private methods and the useful comments πŸ˜‰

  4. Eric Hynds

    I’m a huge fan of exposing the default options in case users want to change a default for all future instances, rather than each time per instance. Something like:

    $.fn.pluginName.defaults = {
       ...
    };
    1. voigtan

      I agree, using something like your code but with a default global so you can rewrite default codes.

      I also a bit lazy adding a variable called pluginName and name my plugin that way and call it:

      $.fn[pluginName] = function ( method ) { /* ...*/};
  5. Steven Black

    A few more refinements to suggest:

    This line can go outside the $.each() since the options are passed-in once per call.

    settings = $.extend({}, defaults, options)

    Also, it may be advisable to expose the defaults so they can be set on an instance-global basis at the user’s discretion. Otherwise the user needs to specify every option for each call.

    $.ajaxSetup() is a practical example of this though, for normal plugins, it’s OK to just poke values into objects.

    Therefore we could have two buckets: plugin author defaults ( a var ) and plugin instance defaults ( exposed ) where at init the plugin instance defaults are set to the plugin author defaults, and thereafter the plugin instance defaults are mutable.

    1. Zachery Hostens

      I’d second this. and people can watch it in case there ever are any changes to it.

    2. Rizky

      +1 for github.. at least make it into a gist. this kinda thing don’t really need a standalone repo.

  6. Rob L.

    Very nice and will definitely use/watch this if you add it to github as mentioned above. One thing that wasn’t really my favorite:

    // "element" holds the jQuery version of the current DOM element
    // "this" refers to the actual DOM element
    var element = $(this);
    

    I really don’t like using “element” to describe something that is a jQuery object instance and not an actual DOM element. I’ve seen (and used) a pattern like this that some of the readers of this post might prefer:

    var 
        elem = this,
        $elem = $(this);
    
    1. Stefan Gabos Post author

      Agree. Updated the code. Thanks!
      I’m not sure with the variable names though πŸ™‚ Maybe we can come up with something better? “element”, “elem”, “el” or something else. Any suggestions?

  7. Gary

    What timing! I needed a jQuery plugin boilerplate… and since there wasn’t one before, I’ve just spent a week developing a plugin without one!!!
    Thanks for this though, it’ll come in handy next time around. πŸ˜‰

  8. Shinya

    Doesn’t this code re-define everything every time $.pluginname() is called? You should probably move all the var declarations outside of $.fn.pluginName = function(method) {.

    1. Stefan Gabos Post author

      it does! In an OOP world every instance of an object should encapsulate everything related to it. I used MooTools like forever and now, transitioning to jQuery, I find confusing the fact that we don’t have “real” objects (apart from the fact that in JavaScript everything is an object). Indeed, jQuery, changes “the way you write JavaScript” (which it shouldn’t) πŸ™‚

      I’m new to jQuery and things are different. Maybe you’re right. Do you have some examples where this would make sense?

    1. Stefan Gabos Post author

      I am using JavaScript since around 1998 – so I can’t say I am new to it πŸ™‚ I am using MooTools since 2006 and love it because it stays true to JavaScript and it doesn’t “change the way you write JavaScript”.

      I started the jQuery plugin boilerplate *because* there wasn’t enough for me http://docs.jquery.com/Plugins/Authoring.

      When I asked for examples, I meant examples about where *not* encapsulating a plugin’s properties in itself would make sense.

  9. JohannC

    Hi,
    First, it is a really good job. It’s very clear for beginning a new plugin.
    In my side, I made some modifications to figure out some issues with the multiple invocations of the plugin. As I am not really expert on Jquery (and javascript), I don’t know if those modifications are really good things. Anyway…
    1. Like Roger Padilla, I put the private methods, the settings and defaults objects out of the plugin name function. No need to re-define everything of them after each invocation and after each public methods call.
    2. Of course, each private method has a “$this” parameter as first argument for dealing with the plugin.
    3. At least, and it is my main issue: in the init method, I save the settings object into $(this).data(“settings”). It is the only way I found to be able to get the settings back in a public method laterly called.

    Sorry for my english.

    1. Stefan Gabos Post author

      I also realized yesterday that currently settings gets overwritten every time you make a call to one of the plugin’s methods from outside the plugin – I’m not yet used to the “everything is a function” approach of jQuery πŸ™‚

      yes, one solution would be to use data. i’ll do some more research for a good solution and post it these days.

      thanks for the feedback!

  10. Roger padilla

    This plugin continue applying several bad practices like putting methods/class-variables/instance-variables declaration inside the main function (the plugin function).

    A very bad consequence of doing such thing is the methods and variables declarations will gets overwritten on every call to the plugin.

    In short, the plugin function should not declare methods/class-variables/instance-variables inside its body; the plugin function is just that, the main, it is the place to start controlling the workflow and delegating responsibilities.

    This will be useful:
    http://docs.jquery.com/Plugins/Authoring

    1. Roger padilla

      Unfortunately that revisited version does not correct the main mistakes made on this version, indeed, that new version adds new problems since it create a new instance of the whole plugin for each invocation.

    2. Stefan Gabos Post author

      I appreciate your feedback but http://docs.jquery.com/Plugins/Authoring is not what I need: I need public and private methods and public and private properties; i need easily maintainable code. Everyone should use what best fits for him πŸ˜‰ I agree though, that the plugin creates a new instance of the plugin on each invocation unless used otherwise than indicated – I will fix that. Thanks!

Comments are closed.