Skip to content

Instantly share code, notes, and snippets.

@antennaio
Created October 11, 2012 10:51
Show Gist options
  • Save antennaio/3871611 to your computer and use it in GitHub Desktop.
Save antennaio/3871611 to your computer and use it in GitHub Desktop.
jQuery Plugin Boilerplate
/**
* jQuery Plugin Boilerplate
*
* Call the plugin by supplying a method and/or options:
*
* $("element").myplugin();
* $("element").myplugin({ option1: true, option2: true });
* $("element").myplugin("secondary_method");
* $("element").myplugin("secondary_method", { option1: true, option2: true });
*
*/
(function ($) {
var MyPlugin, root;
root = typeof window !== "undefined" && window !== null ? window : global;
root.MyPlugin = MyPlugin = (function () {
function MyPlugin() {
// this method will be called by default if no other method is specified explicitly
this.primary_method = function () {
// this.elem holds the element
console.log (this.elem);
// this.options holds the options
console.log (this.options);
}
this.secondary_method = function () {
// you can put many methods on the plugin
}
}
MyPlugin.prototype.init = function (options, elem) {
var self;
self = this;
self.elem = elem;
return self.options = $.extend({}, $.fn.myplugin.defaults, options);
};
return MyPlugin;
})();
$.fn.myplugin = function (method, options) {
return this.each(function () {
var plugin = new MyPlugin();
// method supplied and exists
if (plugin.hasOwnProperty(method)) {
plugin.init(options, this);
return plugin[method]();
// only options supplied
} else if (typeof method === 'object') {
options = method;
plugin.init(options, this);
return plugin.primary_method();
// no method supplied
} else if (!method) {
plugin.init({}, this);
return plugin.primary_method();
} else {
$.error('Method ' + method + ' does not exist on jQuery.myplugin');
}
});
};
// default options
return $.fn.myplugin.defaults = {
option1:false,
option2:false
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment