Last active
October 5, 2017 17:37
-
-
Save james4388/a0ad0b41c61a3da0b2c0334818d0c8cb 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
;(function($, window, document, undefined) { | |
"use strict"; | |
// Default options | |
var pluginName = "pluginName", //plugin name that will be use in $(element).pluginName | |
defaults = { | |
// Options | |
// Events | |
}; | |
function MyPlugin(element, options) { | |
this.element = element; // The element in $(element).pluginName() | |
this.settings = $.extend({}, defaults, options); | |
this._defaults = defaults; | |
this._name = pluginName; | |
this.init(); | |
} | |
// Methods | |
$.extend(MyPlugin.prototype, { | |
init: function() { | |
} | |
}); | |
$.fn[pluginName] = function(options) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
return this.each(function() { | |
if (typeof(options) === "string") { | |
if (!$.data(this, "plugin_" + pluginName)) { | |
$.error("Initialize container before invoke methods"); | |
} else { | |
var plugin = $.data(this, "plugin_" + pluginName); | |
if (options[0] !== '_' && plugin[options] && typeof(plugin[options]) === 'function'){ | |
// Not allow to call private method that start with _ | |
plugin[options].apply(plugin, args); | |
} else { | |
$.error('Method "' + options + '" does not exist on jQuery.' + pluginName); | |
} | |
} | |
} else { | |
if (!$.data(this, "plugin_" + pluginName)) { | |
$.data(this, "plugin_" + pluginName, new MyPlugin(this, options)); | |
} | |
} | |
}); | |
}; | |
})(jQuery, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment