Skip to content

Instantly share code, notes, and snippets.

@anandgorantala
Last active December 16, 2015 09:58
Show Gist options
  • Save anandgorantala/5416353 to your computer and use it in GitHub Desktop.
Save anandgorantala/5416353 to your computer and use it in GitHub Desktop.
jQuery plugin pattern
(function ($, window) {
"use strict";
var pluginName = 'pluginName', // Your plugin namespace.
defaults = { // Declare your plugin defaults here.
'foo': 'bar'
},
Plugin = function (element, options) {
var $element = $(element),
state = {}, // An object representing the current state/status
cache = { // Cache your DOM lookups and any other variables eg., lengths of arrays, etc.
$window : $(window),
$document : $(document),
$body : $('body')
},
getOptions = function () {
return options;
},
getState = function () {
return state;
},
// Add the rest of your plugin logic and functions above this code,
// so they are declared before they are used below.
setupEventHandlers = function () {
// Add all the plugin event handlers here.
},
create = function () {
setupEventHandlers();
return this;
},
destroy = function () {
};
return { // Expose your plugin's public methods.
getOptions: getOptions,
getState: getState,
create: create,
destroy: destroy
};
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$(this).data(pluginName)) {
options = $.extend({}, defaults, options);
$(this).data(pluginName, new Plugin(this, options).create());
}
});
};
$.fn[pluginName].defaults = defaults;
}(jQuery, window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment