Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery plugin template
/**
* jQuery plugin template by https://github.com/publicJorn
* Features:
* - dynamic plugin name (only supply once) so it's easy to change later
* - plugin factory to make it work in the browser, or with AMD / COMMONJS modules
* - Plugin instance is saved on the selector element
* - Default options are saved to the instance in case you need to figure out a difference between passed options
*/
(function(global, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], function($) {
return factory($, global, global.document);
});
} else if (typeof exports === "object" && exports) {
module.exports = factory(require('jquery'), global, global.document);
} else {
factory(jQuery, global, global.document);
}
})(typeof window !== 'undefined' ? window : this, function($, window, document, undefined) {
'use strict';
// -- Name is used to keep jQUery plugin template portable
var pluginName = 'pluginName';
// -- Globals (shared across all plugin instances)
var defaultOptions = {};
var $window = $(window);
var $document = $(document);
// -- Plugin constructor
// Using p object as placeholder, together with pluginName to make jQuery plugin template portable
var p = {}; p[pluginName] = function (el, options) {
this.el = el;
this.options = $.extend({}, defaultOptions, options) ;
this._defaultOptions = defaultOptions;
this.init();
}
// Rest of the functions
p[pluginName].prototype = {
/**
*
*/
init: function() {
console.info('initialised');
}
};
// -- Prevent multiple instantiations
$.fn[pluginName] = function(options) {
return this.each(function () {
if (!$.data(this, 'plugin_'+ pluginName)) {
$.data(this, 'plugin_'+ pluginName, new p[pluginName](this, options));
}
});
};
});
@publicJorn
Copy link
Author

publicJorn commented Oct 24, 2016

If you are interested, there's also an ES6 version
Note that it requires a build step to transpile to ES5 if you intend to use it directly in the browser. Use webpack or browserify for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment