Here is the official jquery plugin guide.
The part about wrapping functions is found here ("Plugin Methods") (the example is a would-be tooltip plugin) :
(function( $ ){
var methods = {
init : function(options) { ... },
show : function() { ... },
hide : function() { ... },
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);
[update] explaining the methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ))
line in the guide :
If you call $(selector).tooltip('update', 'hello')
from your javascript code, you want to end up calling the update
method, passing 'hello'
as the content
argument, with this
set to $(selector)
for the duration of the call.
That is what this line takes care of :
- if
method == 'update'
, methods[method]
is the update
method,
arguments
will be equal to ['update', 'hello']
, you have to drop the first element to get the arguments you want to pass to your method ; this is exactly what Array.prototype.slice.call(arguments, 1)
does,
myFunc.apply(obj, argsArray)
calls the function myFunc
, passing argsArray
as the arguments, and setting this
to obj
for the duration of the call.
So inside your methods, you can call this.each(...)
to iterate over all of the selector's items, e.g. :
update: function(content) {
this.each(function(){ $(this).data('tooltip.content', content); });
return this;
}