I'm not sure how the jQuery user interface is (you should look at the source), but here is a way to do it https://gist.github.com/elclanrs/5668357
The advantage of using this approach is that you keep all of your methods private, rather than prototype, using closure; module template in this case.
Edit: Aight, got it. This is how I earned it. This I call "Advanced jQuery Boilerplate". I added methods to the prototype, I donβt think it really matters to keep them outside, and it simplifies calling methods in methods using this.method() :
(function($) { var _pluginName = 'myplugin' , _defaults = { }; function Plugin(el, options) { this.opts = $.extend({}, _defaults, options); this.el = el; this._init(); } Plugin.prototype = { _init: function() { return this; }, method: function(str) { console.log(str); return this; } }; Plugin.prototype[_pluginName] = function(method) { if (!method) return this._init(); try { return this[method].apply(this, [].slice.call(arguments, 1)); } catch(e) {} finally { return this; } }; $.fn[_pluginName] = function() { var args = arguments; return this.each(function() { var instance = $.data(this, 'plugin_'+ _pluginName); if (typeof args[0] == 'object') { return $.data(this, 'plugin_'+ _pluginName, new Plugin(this, args[0])); } return instance[_pluginName].apply(instance, args); }); }; }(jQuery));
Now I have two divs:
<div></div> <div id="mydiv"></div>
And I can use the plugin like:
$('div').dialog({ n: 69 }); // initialize both divs console.log($('#mydiv').dialog('method', 'hello world')); //=^ prints "hello world" and returns instance console.log($('#mydiv').data('plugin_dialog').opts.n); //=> 69
It basically saves the plugin instance in data in order to be able to restore the parameters, since this information is bound to the element. This is similar to how jQuery Boilerplate works .