Created
August 16, 2009 19:44
-
-
Save boucher/168735 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @import <Foundation/CPObject.j> | |
| // bad class name. need something better. | |
| @implementation CPFunctionForwarder : CPObject | |
| { | |
| CPDictionary _implementations; | |
| } | |
| - (id)init | |
| { | |
| if (self = [super init]) | |
| _implementations = [CPDictionary dictionary]; | |
| return self; | |
| } | |
| // used like this: | |
| // [CPFunctionForwarder objectWithFunctionsForSelectors: | |
| // function(self, cmd, foo, bar, baz) {}, | |
| // @"methodWithParameter:andAnother:lastOne:"]; | |
| // | |
| // obviously, you can respond to as many selectors as you like | |
| // debatable whether or not to strip self and cmd from the params | |
| + (id)objectWithFunctionsForSelectors:(id)anObject,... | |
| { | |
| var object = [[self alloc] init]; | |
| for(var i = 2; i < arguments.length; i+=2) | |
| { | |
| var selector = arguments[i], | |
| implementation = arguments[i+1]; | |
| if (!selector || !implementation) | |
| break; | |
| [_implementations setValue:implementation forKey:selector]; | |
| } | |
| return object; | |
| } | |
| - (void)forwardInvocation:(CPInvocation)anInvocation | |
| { | |
| var implementation = [_implementations objectForKey:[anInvocation selector]]; | |
| if (implementation) | |
| { | |
| var returnValue = implementation.apply(self, [anInvocation arguments]); | |
| [anInvocation setReturnValue:returnValue]; | |
| } | |
| else | |
| [super forwardInvocation:anInvocation]; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment