Skip to content

Instantly share code, notes, and snippets.

@mx-moth
Last active December 31, 2015 05:19
Show Gist options
  • Save mx-moth/7939909 to your computer and use it in GitHub Desktop.
Save mx-moth/7939909 to your computer and use it in GitHub Desktop.
My preferred jQuery plugin boilerplate. Copy this in, replace 'pluginName'/PluginClass with your preferred name, and go
(function($) {
"use strict";
var pluginName = 'pluginName';
var PluginClass = function(el, options) {
this.$el = $(el);
// Set options for this instance, inheriting from the default options
this.opts = $.extend({}, plugin.defaults, options);
// Set up everything else
this.bindEvents();
};
// Define class methods as normal, using PluginClass.prototype.name
/* Set up event listeners */
PluginClass.prototype.bindEvents = function() {
// For example, bind to the click event
this.$el.click(function() {})
};
/* Do something to this instance */
PluginClass.prototype.doSomething = function(name, options) {
this.$el.text(name);
this.$el.attr(options);
};
// The following functions, on the PluginClass object itself, will be callable
// using the pattern:
//
// $el.pluginName('doSomething', arg1, arg2, ...);
/* Do something to all of the elements in $els */
PluginClass.doSomething = function($els, name, options) {
$els.each(function() {
PluginClass.getOrCreate(this).doSomething(name, options);
});
return $els;
}
/* Create - or return the existing - instance of PluginClass for this element */
PluginClass.getOrCreate = function(el, options) {
var rev = $(el).data(pluginName);
if (!rev) {
rev = new PluginClass(el, options);
$(el).data(pluginName, rev);
}
return rev;
};
/*
* Expose the plugin to jQuery. It can be started using $el.pluginName([options]).
*
* Methods exposed above on the PluginClass object will be accessible using
*
* $el.pluginName('methodName', arg1, arg2);
*/
var plugin = $.fn[pluginName] = function() {
var options, fn, args;
// Create a new PluginClass for each element in the selector
if (arguments.length === 0 || (arguments.length === 1 && $.type(arguments[0]) != 'string')) {
options = arguments[0];
return this.each(function() {
return PluginClass.getOrCreate(this, options);
});
}
// Call a function on each PluginClass in the selector
fn = arguments[0];
args = $.makeArray(arguments).slice(1);
if (fn in PluginClass) {
// Call the PluginClass class method if it exists
args.unshift(this);
return PluginClass[fn].apply(PluginClass, args);
} else {
throw new Error("Unknown function call " + fn + " for $.fn." + pluginName);
}
};
// Expose the PluginClass and defaults, accessibly via $.fn.pluginName.PluginClass
plugin.PluginClass = PluginClass;
plugin.defaults = {
// default options
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment