Last active
August 29, 2015 14:08
-
-
Save htmlr/84cbefff44fd50157c80 to your computer and use it in GitHub Desktop.
jQuery Plugin Boilerplate
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 Boilerplate | |
| Thanks to http://stackoverflow.com/a/22976877/417933 | |
| */ | |
| (function($) { | |
| var CustomPlugin = function($el, options) { | |
| this._defaults = { | |
| randomizer: Math.random() | |
| }; | |
| this._options = $.extend(true, {}, this._defaults, options); | |
| this.options = function(options) { | |
| return (options) ? | |
| $.extend(true, this._options, options) : | |
| this._options; | |
| }; | |
| this.move = function() { | |
| $el.css('margin-left', this._options.randomizer * 100); | |
| }; | |
| }; | |
| $.fn.customPlugin = function(methodOrOptions) { | |
| var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined; | |
| if (method) { | |
| var customPlugins = []; | |
| function getCustomPlugin() { | |
| var $el = $(this); | |
| var customPlugin = $el.data('customPlugin'); | |
| customPlugins.push(customPlugin); | |
| } | |
| this.each(getCustomPlugin); | |
| var args = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : undefined; | |
| var results = []; | |
| function applyMethod(index) { | |
| var customPlugin = customPlugins[index]; | |
| if (!customPlugin) { | |
| console.warn('$.customPlugin not instantiated yet'); | |
| console.info(this); | |
| results.push(undefined); | |
| return; | |
| } | |
| if (typeof customPlugin[method] === 'function') { | |
| var result = customPlugin[method].apply(customPlugin, args); | |
| results.push(result); | |
| } else { | |
| console.warn('Method \'' + method + '\' not defined in $.customPlugin'); | |
| } | |
| } | |
| this.each(applyMethod); | |
| return (results.length > 1) ? results : results[0]; | |
| } else { | |
| var options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined; | |
| function init() { | |
| var $el = $(this); | |
| var customPlugin = new CustomPlugin($el, options); | |
| $el.data('customPlugin', customPlugin); | |
| } | |
| return this.each(init); | |
| } | |
| }; | |
| })(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment