Skip to content

Instantly share code, notes, and snippets.

@bethrezen
Last active May 23, 2017 13:29
Show Gist options
  • Select an option

  • Save bethrezen/8869437e77b5dc255b360a53aea7cd8c to your computer and use it in GitHub Desktop.

Select an option

Save bethrezen/8869437e77b5dc255b360a53aea7cd8c to your computer and use it in GitHub Desktop.
ES6-style jQuery plugin definition
/**
* Generate a jQuery plugin
* Based on https://gist.github.com/monkeymonk/c08cb040431f89f99928132ca221d647
* @param pluginName [string] Plugin name
* @param ClassName [object] Class of the plugin
* @param shortHand [bool] Generate a shorthand as $.pluginName
*
* @example
* import plugin from 'plugin';
*
* class MyPlugin {
* constructor(element, options) {
* // Do not forget this just in case of something goes wrong
* this.$element = $(element);
* // ...
* }
* }
*
* MyPlugin.DEFAULTS = {};
*
* plugin('myPlugin', MyPlugin');
*
* Example use:
* - Init plugin: `$('.element').myPlugin({options: 'here'});`
* - Call class function `$('.element').myPlugin('functionName', argument1, argument2);`
* - Get class property in callback `$('.element').myPlugin('propertyName', function(value) {console.log(value);});`
*/
export default function plugin(pluginName, ClassName, shortHand = false) {
const dataName = `__${pluginName}`;
const old = $.fn[pluginName];
$.fn[pluginName] = function (option, ...args) {
return this.each(function () {
const $this = $(this);
let data = $this.data(dataName);
const options = $.extend({}, ClassName.DEFAULTS, $this.data(), typeof option === 'object' && option);
if (!data) {
$this.data(dataName, (data = new ClassName(this, options)));
}
if (typeof option === 'string') {
if (typeof data[option] === 'function') {
data[option](...args);
} else {
args[0](data[option]);
}
}
});
};
// - Short hand
if (shortHand) {
$[pluginName] = (options) => $({})[pluginName](options);
}
// - No conflict
$.fn[pluginName].noConflict = () => {
$.fn[pluginName] = old;
return $.fn[pluginName];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment