Created
August 21, 2019 04:05
-
-
Save edison7500/3047f9a69b1db741ff387fd0ad5b7e1c to your computer and use it in GitHub Desktop.
jquery.plugin.js
This file contains hidden or 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"; | |
/** | |
* Generate a jQuery plugin | |
* @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) { | |
* // ... | |
* } | |
* } | |
* | |
* MyPlugin.DEFAULTS = {}; | |
* | |
* plugin('myPlugin', MyPlugin'); | |
*/ | |
export default function plugin(pluginName, className, shortHand = false) { | |
let dataName = `__${pluginName}`; | |
let old = $.fn[pluginName]; | |
$.fn[pluginName] = function (option) { | |
return this.each(function () { | |
let $this = $(this); | |
let data = $this.data(dataName); | |
let options = $.extend({}, className.DEFAULTS, $this.data(), typeof option === "object" && option); | |
if (!data) { | |
$this.data(dataName, (data = new className(this, options))); | |
} | |
if (typeof option === "string") { | |
data[option](); | |
} | |
}); | |
}; | |
// - Short hand | |
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