Skip to content

Instantly share code, notes, and snippets.

@benjasHu
Last active March 13, 2021 07:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save benjasHu/9224d60fe0da10e697a1 to your computer and use it in GitHub Desktop.
Save benjasHu/9224d60fe0da10e697a1 to your computer and use it in GitHub Desktop.
ES6 Module jQuery Plugin Definition
import pluginify from 'pluginify';
class Plugin {
constructor() {
/* ... */
}
}
/*
Convert plugin class into a jQuery plugin
*/
pluginify('pluginName', 'pluginDataName', Plugin, true);
import $ from 'jquery';
export default function jQueryPluginDefinition( ...args ) {
let [ pluginName, dataName, ClassName, shorthand=false ] = args,
old = $.fn[pluginName];
$.fn[pluginName] = function( options={} ) {
return this.each(( i, el ) => {
let $this = $(el),
data = $this.data(dataName);
if (typeof options === "object") {
if( !data ) $this.data(dataName, new ClassName($.extend(options, {el:$this})));
} else {
if (data && data[options]) return data[options].apply(data, options);
}
});
};
// SHORTHAND
if(shorthand) $[pluginName] = ( options ) => $({})[pluginName](options);
// NO CONFLICT
$.fn[pluginName].noConflict = () => $.fn[pluginName] = old;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment