The “official” documentation http://docs.jquery.com/Plugins/Authoring#Namespacing states that methods should be added to a jQuery plugin as shown below. I haven’t seen this design pattern implemented often. It seems like if other plugins use var method, there might be conflicts. Is this really the preferred method, or should I be doing it differently?
(function( $ ){
var methods = {
method1: function( options ) {},
method2: function( ) {}
};
$.fn.tooltip = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
}
};
})( jQuery );
If you want to make the methods publically accssible then yes, it is the preferred method. The other option that is possible and sometimes advisable if the plugin is extremely complex is to actually create a full constructed object instead of just using a methods hash. I dont know that that really needs to be done anymore because you can manage state usin
.data()on the root element of each instance but its a pattern ive seen and also appreciated before.<rant>Additionally, I have had aggravation of late with a lot of plugins… please if you are going to open source it make sure you at least include a
destroymethod to unbind everything you have done.</rant>