Reputation: 442
I'm toying around a bit with authoring plugins so I turned to the jQuery documentation where it was talking about not cluttering the $.fn object and how no single plugin should ever claim more than on $.fn namespace...
(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 );
// calls the init method
$('div').tooltip();
// calls the init method
$('div').tooltip({
foo : 'bar'
});
I understood everything up until the:
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
part.
I changed that bit to simply:
$.fn.tooltip = function(method)
{
if(myFunc[method])
{
return myFunc[method].apply();
}
}
and it works just fine... Can someone please explain to me exactly what's going on there and why mine seemed to work just fine?
EDIT: By the way, I know I didn't continue the if/else structure entirely, that's because I'm purely focused on the line I mentioned and not the remaining part of the if structure.
Upvotes: 0
Views: 172
Reputation: 95022
Your way of doing it works fine, however, it won't allow you to pass any parameters on to your methods.
For example, If your plugin had an option
method that allowed you to change the tooltip text option, you would call it like this:
$(element).tooltip("option","text","foobar!!");
If you remove all that other code and use your way of doing it, the option
method wouldn't receive the "text"
or "foobar!!!"
parameters.
Upvotes: 1