Skip to content

Instantly share code, notes, and snippets.

@akger1379
Last active January 4, 2016 12:59
Show Gist options
  • Save akger1379/8625327 to your computer and use it in GitHub Desktop.
Save akger1379/8625327 to your computer and use it in GitHub Desktop.
A solid starter template for your jQuery plugins. Inspired by https://github.com/jquery-boilerplate/jquery-boilerplate
/**
* JPB - JQUERY PLUGIN BOILERPLATE
* A solid starter template for your jQuery plugins.
* Inspired by http://jqueryboilerplate.com
* @copyright André Kroll
* @license MIT
*/
;
(function ($, window, document, undefined) {
var PLUGIN_NAME = 'my_plugin'; // (i) will give you later access with: $('div').my_plugin()
var PLUGIN_DEFAULTS = {}; // (i) set plugin default options
function PLUGIN(element, options) {
this._$element = $(element);
this._options = this._validateOptions(options, PLUGIN_DEFAULTS);
// (i) put your constructor logic here ...
};
PLUGIN.prototype = {
// <PUBLIC_PLUGIN_LOGIC> ...........................................................................................
helloWorld: function () {
alert('Hello World!');
},
// <PRIVATE_PLUGIN_LOGIC> ..........................................................................................
// Validate options and merge with defaults
_validateOptions: function (options, defaults) {
// (i) put your option validation logic here ...
return $.extend({}, defaults, options);
}
};
// <PRIVATE_STATIC_HELPERS> ..........................................................................................
{
// Simple and safe function to log/debug elements
function log(varToLog) {
if (window.console && window.console.log) {
window.console.log(varToLog);
}
}
}
// <JPB_CORE> ......................................................................................................
{
// Register global access through window object for altering plugin defaults
window[PLUGIN_NAME + '_defaults'] = PLUGIN_DEFAULTS;
// Register the plugin at jQuerys function namespace
$.fn[PLUGIN_NAME] = function () {
var orgArgs = arguments;
var constructOptions = {};
var isMethodCall = false;
var methodArgs = [];
if (orgArgs[0] !== undefined && typeof orgArgs[0] === 'object') {
constructOptions = orgArgs[0];
} else if (typeof orgArgs[0] === 'string') {
isMethodCall = true;
methodArgs = Array.prototype.slice.call(orgArgs, 1)
}
this.each(function () {
if (undefined === $.data(this, 'plugin_' + PLUGIN_NAME)) {
// First call by this element: create new instance of the plugin
$.data(this, 'plugin_' + PLUGIN_NAME, new PLUGIN(this, constructOptions));
}
if (isMethodCall === true) {
$.data(this, 'plugin_' + PLUGIN_NAME)[orgArgs[0]].apply($.data(this, 'plugin_' + PLUGIN_NAME), methodArgs);
}
});
return this;
};
}
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment