JQuery Plugin Boilerplate

In a previous article I pointed out a great resource for starting your jQuery plugins.

This resource is called Starter and will allow you to pass through your parameters to your plugin and will generate the boilerplate for your jQuery plugin.

Starter

Here is a jQuery snippet for a jQuery plugin boilerplate by Stefan Gabos.

JQuery Plugin Boilerplate

// 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);

How To Use The jQuery Plugin

$(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;

});

Source: http://stefangabos.ro/jquery/jquery-plugin-boilerplate-oop/

Advertise here

Comment