Last active
December 21, 2018 05:46
-
-
Save Maxstupo/bc9b3eaad3be03e949cf7f610fe5c331 to your computer and use it in GitHub Desktop.
A jQuery plugin template.
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
(function ($) { | |
const PLUGIN_NAME = 'myplugin'; // The name of the plugin method. (Function name of the plugin) | |
const DATA_NAME = 'jqp_' + PLUGIN_NAME; // The id of the plugin instance attached to each element that this plugin was initialized on. (https://api.jquery.com/data/) | |
const MyPlugin = function ($el, newOptions) { | |
const _this = this; | |
this.$el = $el; // Expose jQuery object this plugin is attached to. | |
/* ---------------- Options Setup --------------- */ | |
this._defaults = { | |
// Default options. | |
}; | |
this._options = $.extend(true, {}, this._defaults, newOptions); // Merges options with defaults. returns new object. | |
// If new options object is supplied it will be merged with the current options. Returns options. | |
this.options = function(newOptions) { | |
return newOptions ? $.extend(true, _this._options, newOptions) : _this._options; | |
}; | |
/* ----------------- Variables ----------------- */ | |
/* ----------------- Functions ----------------- */ | |
this.demoFunction = function() { | |
console.log('Hello World'); | |
return $el; // Return $el to make this function chainable (e.g. $('body').myplugin('demoFunction').myplugin('instance'); ) | |
}; | |
this.instance = function () { | |
return _this; | |
}; | |
}; | |
$.fn[PLUGIN_NAME] = function (methodOrOptions, ...args) { | |
let method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined; | |
if (method) { | |
let customPlugins = []; | |
this.each(function () { | |
let customPlugin = $(this).data(DATA_NAME); | |
customPlugins.push(customPlugin); | |
}); | |
let results = []; | |
this.each(function (index) { | |
let customPlugin = customPlugins[index]; | |
if (!customPlugin) { | |
console.warn('$.' + PLUGIN_NAME + ' not instantiated yet!'); | |
console.info(this); | |
results.push(undefined); | |
return; | |
} | |
if (typeof customPlugin[method] === 'function') { | |
let result = customPlugin[method].apply(customPlugin, args); | |
results.push(result); | |
} else { | |
console.warn('Method \'' + method + '\' not defined in $.' + PLUGIN_NAME); | |
} | |
}); | |
return (results.length > 1) ? results : results[0]; | |
} else { | |
let options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined; | |
return this.each(function () { | |
let $el = $(this); | |
let customPlugin = new MyPlugin($el, options); | |
$el.data(DATA_NAME, customPlugin); | |
}); | |
} | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment