Writing jQuery plugins

There are a few simple rules to writing jQuery plugins which prevent issues later down the line.

1) start with an IIFE which passes through jQuery into its scope

(function($, window, undefined) {
// your plugin will go here 
}(jQuery, window));

2) Define your plugin functions as an object inside those brackets

var module = {
name: 'Carousel',
  defaults: {
    propertyName: 'value'
  },
init: function() {
// put your init code here
},
update: function() {}
}

3) Then register your module object as a function prototype so we can have multiple instances

function Plugin(element, options) {
    this.el = element;
    this.options = $.extend({}, module.defaults, options);
    this.init();
}
Plugin.prototype = module;

4) Then register as a jquery plugin with some code to test whether it has already been init'd on that element before

$.fn[module.name] = function(options) {
    var args = arguments;
    if (options === undefined || typeof options === 'object') {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + module.name)) {
                $.data(this, 'plugin_' + module.name, new Plugin(this, options));
            }
        });
    } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
        return this.each(function() {
            var instance = $.data(this, 'plugin_' + module.name);
            if (instance instanceof Plugin && typeof instance[options] === 'function') {
                instance[options].apply(instance, Array.prototype.slice.call(args, 1));
            }
        });
    }
}

5) Then call your plugin on elements to load it

$('#example').Carousel({optionparam: 'example'});

6) To call another function you can use the format:

$('#example').Carousel('update', {newparam2: 'another example'});

No comments:

Post a Comment