Or better yet, see below. You guys are better at overloading so I trust you'll figure a way to remove the switch statement :-)
- (function($){
- $.fn.method = function( type, name, rest ){
- switch( type ){
- case 'set':
- //Set the method for each.
- return this.data('method_' + name, typeof rest == 'string' ? new Function(rest) : rest);
- case 'get':
- //Run the method and return its result set, as an array if more than one in this.
- case 'run':
- //Run the method but return this for continued chaining.
- var args = [];
- for( var i = 2; i < arguments.length; i++ )
- args.push(arguments[i]);
- if( type == 'run' )
- return this.each(function(){
- $(this).data('method_' + name).apply(this, args);
- });
- else if( this.length == 1 )
- return this.data('method_' + name).apply(this.get()[0], args);
- else if( this.length > 1 ){
- var all = [];
- this.each(function(){
- all.push( $(this).data('method_' + name).apply(this, args) );
- })
- return all;
- }
- else
- return this;
- default:
- alert('Unknown method action: ' + type + ' on ' + name + '.');
- return this;
- }
- };
- })($);