Skip to content

Instantly share code, notes, and snippets.

@publicJorn
Last active June 4, 2023 21:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save publicJorn/668d381287632b1fbaed2d5288340b25 to your computer and use it in GitHub Desktop.
Save publicJorn/668d381287632b1fbaed2d5288340b25 to your computer and use it in GitHub Desktop.
jQuery plugin template ES6
/**
* jQuery plugin template by https://github.com/publicJorn
* Features:
* - ES6 (So, it requires a build step to transpile to ES5 for most environments)
* - 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
const pluginName = 'pluginName';
// -- Globals (shared across all plugin instances)
const defaultOptions = {};
const $window = $(window);
const $document = $(document);
// -- Plugin constructor
// Using p object as placeholder, together with pluginName to make jQuery plugin template portable
const p = {}; p[pluginName] = class {
constructor (el, opts) {
this.el = el;
this.opts = $.extend({}, defaultOptions, opts) ;
this._defaultOptions = defaultOptions;
this.init();
}
init () {
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

Note that this requires a build step to transpile to ES5. For instance, use webpack or browserify.

There's also an ES5 version, if you intend to only use this plugin directly in the browser.

@tonix-tuft
Copy link

If we use this template for a jQuery plugin, then how does the client code uses our plugin when working with ES6 too?

Will this work (assuming the plugin is published to NPM with the name jquery-plugin-name):

// client code using plugin.
import $ from "jquery";
import "jquery-plugin-name";

$('.some-class'). pluginName(); // Will it work?

?

Thank you!

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