Skip to content

Instantly share code, notes, and snippets.

@skhilko
Last active October 11, 2015 12:58
Show Gist options
  • Save skhilko/3863047 to your computer and use it in GitHub Desktop.
Save skhilko/3863047 to your computer and use it in GitHub Desktop.
jQuery: Plugin Boilerplate
/**
* jQuery Plugin Boilerplate
* Author: Sergey Khilko
*
* Usage Examples:
* $('#id').pluginName({ option: 'value' });
* $('#id').pluginName('function', arg1, arg2);
* $('#id').data("pluginName").function(arg1, arg2);
*
* Based on:
* https://github.com/zenorocha/jquery-boilerplate
* https://gist.github.com/1348382
*/
;(function($, window, undefined) {
var pluginName = 'pluginName',
defaults = {
};
function Plugin(element, options) {
// this.element is jQuery wrapper
this.element = element;
this.options = $.extend(true, {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function() {
// Place initialization logic here
// You already have access to the DOM element and the options via the instance,
// e.g., this.element and this.options
};
Plugin.prototype.destroy = function() {
this.element = null;
$.removeData(this.element[0], 'plugin_' + pluginName);
};
$.fn[pluginName] = function(options) {
var args = arguments;
if(options === undefined || typeof options === 'object') {
return this.each(function() {
if(!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin($(this), options));
}
});
} else if(typeof options === 'string' && options[0] !== '_' && options !== 'init') {
return this.each(function() {
var instance = $.data(this, 'plugin_' + pluginName);
if(instance instanceof Plugin && typeof instance[options] === 'function') {
instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
});
}
};
}(jQuery, window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment