Created
October 4, 2012 05:16
-
-
Save jonpacker/3831607 to your computer and use it in GitHub Desktop.
Event base class for objective c
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/Foundation.h> | |
| // I did not steal this from Node.js. I promise. No way. Would never do that. Definitely not. Ok I did. Shut up. | |
| typedef void (^JPEventBlock)(NSError* errorOrNil, id accompanyingDataOrNil); | |
| @interface JPEventedObject : NSObject { | |
| @private | |
| NSMutableDictionary* _listeners; | |
| } | |
| - (void) addListener:(JPEventBlock)callback forEventName:(NSString *)eventName; | |
| - (void) fireListenersForEvent:(NSString *)event withErrorOrNil:(NSError *)error andAccompanyingDataOrNil:(id)data; | |
| @end |
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 "JPEventedObject.h" | |
| @implementation JPEventedObject | |
| - (id) init { | |
| if ((self = [super init]) != nil) { | |
| _listeners = [[NSMutableDictionary alloc] init]; | |
| } | |
| return self; | |
| } | |
| - (void) addListener:(JPEventBlock)callback forEventName:(NSString *)eventName { | |
| NSMutableArray* listenersForEvent = [_listeners objectForKey:eventName]; | |
| if (listenersForEvent == nil) { | |
| listenersForEvent = [[NSMutableArray alloc] init]; | |
| [_listeners setObject:listenersForEvent forKey:eventName]; | |
| } | |
| [listenersForEvent addObject:[callback copy]]; | |
| } | |
| - (void) fireListenersForEvent:(NSString *)event withErrorOrNil:(NSError *)error andAccompanyingDataOrNil:(id)data { | |
| NSArray* listeners = [_listeners objectForKey:event]; | |
| if (listeners == nil) { | |
| return; | |
| } | |
| [listeners enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { | |
| void (^listener)(NSError*, id) = obj; | |
| listener(error, data); | |
| }]; | |
| } | |
| @end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
P.S. this uses ARC. It will leak memory all over your face otherwise.