Skip to content

Instantly share code, notes, and snippets.

@tytskyi
Last active August 29, 2015 14:11
Show Gist options
  • Save tytskyi/6fce6db32120082fb562 to your computer and use it in GitHub Desktop.
Save tytskyi/6fce6db32120082fb562 to your computer and use it in GitHub Desktop.
Quickstart jQuery plugin boilerplate.
// Example of creation new plugin based on this one.
(function ($) {
var pluginName = 'myBoilerplate';
var parent = $.fn.boilerplate;
var defaults = {};
var Constructor = function (element, options) {
this.element = element;
this._settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
// Kind of inheritance. Can be omitted.
// Or this.initialize() can be overwriten for this instance.
parent.Constructor.prototype.initialize.apply(this, arguments);
};
// Define all public methods.
var methods = {
message: function (msg) {
console.log(msg);
return this;
}
};
$.extend(Constructor.prototype, methods);
parent.buildPlugin(pluginName, Constructor);
}(jQuery || window.jQuery));
(function ($) {
// Unique name of plugin.
var pluginName = 'boilerplate';
var defaults = {};
// Service function.
var buildPlugin = function (pluginName, Constructor) {
if (typeof $.fn[pluginName] !== 'function') {
$.fn[pluginName] = function (options, params) {
return this.each(function () {
var pluginInstance = $.data(this, pluginName);
var methodName, method;
if (!pluginInstance) {
$.data(this, pluginName, new Constructor(this, options));
} else {
methodName = options;
method = pluginInstance[methodName];
if (typeof methodName === 'string' && typeof method === 'function') {
method(params);
} else {
throw new Error('jQuery.fn.' + pluginName + ': No such method "' + options + '"');
}
}
});
};
// Export Constructor to allow inherit from the plugin.
if (Constructor) {
$.fn[pluginName].Constructor = Constructor;
}
$.prototype[pluginName].buildPlugin = buildPlugin;
return $.fn[pluginName];
} else {
throw new Error('jQuery.fn.' + pluginName + ': is already defined.');
}
};
var Constructor = function (element, options) {
this.element = element;
this._settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
if (typeof this.initialize === 'function') {
this.initialize();
}
};
// Define all public methods.
var methods = {
initialize: function () {
return this;
}
};
$.extend(Constructor.prototype, methods);
// Magic.
buildPlugin(pluginName, Constructor);
}(jQuery || window.jQuery));
var $div = $('<div></div>');
$div.myBoilerplate();
var instance = $div.data('myBoilerplate');
instance.message('Hello world!');
// Below does the same but bit safer (checks if plugin has given method).
$('<div></div>').myBoilerplate().myBoilerplate('message', 'Hello world!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment