EventEmitter for Objective-C that implements the NodeJS EventEmitter API as closely as possible.
The library adds a category to NSObject that allows any object to emit
or listen
to events.
Add it as a Cocoapods dependency to your Podfile:
pod 'Emitter'
Register an event listener on any object:
#import <EventEmitter/EventEmitter.h>
NSObject *server = [[NSObject alloc] init];
[server on:@"connection" listener:^(id stream) {
NSLog(@"someone connected!");
}];
[server once:@"connection" listener:^(id stream) {
NSLog(@"Ah, we have our first user!");
}];
Later, fire an event to the same object:
[server emit:@"connection", stream];
[server emit:@"event", @{
@"type": @"somethinghappened",
@"another key": @"another value",
}];
You can listen for events using:
- (void)addListener:(NSString *)event listener:(id)listener;
- (void)on:(NSString *)event listener:(id)listener;
- (void)once:(NSString *)event listener:(id)listener;
Stop listening with:
- (void)removeListener:(NSString *)event listener:(id)listener;
- (void)removeAllListeners:(NSString *)event;
Emit events with:
- (void)emit:(NSString *)event, ...;
It is also possible to listen for events with a selector and target object using:
- (void)addListener(NSString *)event selector:(SEL)selector target:(id)target;
- (void)on:(NSString *)event selector:(SEL)selector target:(id)target;
- (void)once:(NSString *)event selector:(SEL)selector target:(id)target;
Stop listening with:
- (void)removeListener:(NSString *)event selector:(SEL)selector target:(id)target;
- (void)removeAllListeners:(NSString *)event;
Any callback block you provide will be called with the correct parameters (we used the fantastic BlocksKit to dynamically invoke the callback block).
This means you can emit events with any number of parameters such as:
[object emit:@"event", @"hello", @123, NO, @{ @"key": @"value" }];
and listen for them with:
[object on:@"event", ^(NSString *param1, NSNumber *param2, BOOL param3, NSDictionary *param4){
NSLog(@"Every parameter was passed correctly!");
}];
The original idea was taken from jerolimov's EventEmitter and expanded to support dynamic block arguments and a single method to emit events.