I've been thinking about this over the weekend and came up with a way to write class-based plugins while still following the jQuery convention. Maybe someone else has done this before but I couldn't find any documentation on this subject. The idea is to extend the base jQuery object with the javascript class, and then extend jQuery.fn with a simple method that does nothing but instantiate the class and return "this".
The nice thing about this approach is that you can still make chainable plugins without polluting the jQuery.fn namespace with a ton of methods. $('#mydiv').myplugin().show(); But if you need access to the object, you can use the "new" construct. var myplugin = new $.MyPlugin($('#mydiv')); myplugin.doSomething(); Here is an example plugin that just alerts some text when the selected elements are clicked. But, if you create the plugin object manually with the "new" construct, you can change the message or invoke the alert without the click: (function($){ var Alerter = function(selector, options) { var obj = this; this.settings = { message: 'no message' }; $.extend(this.settings, options); selector.click(function() { obj.alert.call(obj); }); } Alerter.prototype.alert = function() { alert('Alerter said: ' + this.settings.message); } Alerter.prototype.message = function(message) { this.settings.message = message; return this; } $.extend({ Alerter: Alerter }); $.fn.extend({ alerter: function(options) { var alerter = new $.Alerter(this, options); return this; } }); })(jQuery); // Usage as jQuery plugin $('#mydiv').alerter({ message: 'foo' }); // Usage as object var alerter = new $.Alerter($('#anotherdiv'), { message: 'bar' }); // As an object, you can call methods on it easily alerter.message('new message'); alerter.alert(); // alerts "Alerter said: new message" Any thoughts on this approach? -Hector On Sun, Nov 23, 2008 at 5:15 AM, Scott González <[EMAIL PROTECTED]>wrote: > > Providing the method name as the first parameter is a bit awkward, > perhaps looking at the alternatives would help: > > Add namespaces to jQuery. This isn't very jQuery-like. Example: $ > (el).tabs.add(url, label).show(); > > Add a new jQuery method for every plugin instance method. This > pollutes the jQuery namespace, so this should only be done when it > really makes sense. Example: $(el).addTab(url, label); > > Use events. You can bind custom events in a namespace and then have > users interact with your plugin by triggering those events. Example: $ > (el).trigger('add.tabs', url, label); > > There may be other approaches as well. > > The jQuery UI approach allows plugins to expose as many methods as > they want while only using one method in the jQuery namespace. >