“Official” way to author a jQuery Plugin, and maintain chainability

[javascript]
(function( $ ){

var methods = {
init : function( options ) { // THIS },
show : function( ) { // IS },
hide : function( ) { // GOOD },
update : function( content ) { // !!! }
};

$.fn.tooltip = function( method ) {

// Method calling logic
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 );
} else {
$.error( ‘Method ‘ + method + ‘ does not exist on jQuery.tooltip’ );
}

};

})( jQuery );

// USAGE…

$(‘div’).tooltip(); // calls the init method
$(‘div’).tooltip({ // calls the init method
foo : ‘bar’
});
$(‘div’).tooltip(‘hide’); // calls the hide method
$(‘div’).tooltip(‘update’, ‘This is the new tooltip content!’); // calls the update method

// EXAMPLE WITH DEFAULTS / OPTIONS

(function( $ ){

$.fn.tooltip = function( options ) {

var settings = {
‘location’ : ‘top’,
‘background-color’ : ‘blue’
};

return this.each(function() {
// If options exist, lets merge them
// with our default settings
if ( options ) {
$.extend( settings, options );
}

// Tooltip plugin code here

});

};
})( jQuery );

// USAGE

$(‘div’).tooltip({
‘location’ : ‘left’
});
[/javascript]

Leave a Reply