-
-
Save danierdev/543ed871984a941b2a40482535089502 to your computer and use it in GitHub Desktop.
jQuery plugin template ES6
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
/** | |
* 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)); | |
} | |
}); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment