/** * 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](); // Method and array of values for passing else if (plugin.hasOwnProperty(method) && options.length !== undefined) { plugin.init(options, this); return plugin[method].apply(plugin, options); // 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);