I am trying to write a good jQuery Plugin structure. I am trying to follow "best practices" from jQuery.com and others.
But I am little bit confused about prototype.
Should I use it or not? And Is the actual structure looks good or terrible?
Thanks !
(function( $ ){
var defaults = { /* ... */ },
publicMethods = {
add: function(options){
var $this = $(this);
// ...
return $this;
}
},
privateMethods = {
init: function(options) {
var $this = $(this);
return $this;
},
click: function() {
//...
}
};
$.fn.tooltip = function(method) {
var args = arguments;
$(this).each(function() {
if ( publicMethods[method] ) {
return publicMethods[ method ].apply( this, Array.prototype.slice.call( args, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return privateMethods.init.apply( this, args );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
});
};
})( jQuery );
With respect to using the .prototype
of the tooltip
function, that would be useful only if the tooltip function is going to be invoked as a constructor.
Typically as a jQuery plugin, you're only interested in using the object created from the jQuery
constructor, rather than creating your own objects from the plugin function.
There may be occasion to use a constructor somewhere internally in your plugin code, but it typically wouldn't be the actual plugin function itself.