Last active
March 13, 2021 07:36
-
-
Save benjasHu/9224d60fe0da10e697a1 to your computer and use it in GitHub Desktop.
ES6 Module jQuery Plugin Definition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pluginify from 'pluginify'; | |
class Plugin { | |
constructor() { | |
/* ... */ | |
} | |
} | |
/* | |
Convert plugin class into a jQuery plugin | |
*/ | |
pluginify('pluginName', 'pluginDataName', Plugin, true); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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