Skip to content

An event emitter implementation for Objective-C with dynamic block invocation based on the node.js EventEmitter API.

License

Notifications You must be signed in to change notification settings

seegno/emitter-objc

Repository files navigation

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.

Build Status

Install it

Add it as a Cocoapods dependency to your Podfile:

pod 'Emitter'

Use it

Quick Start

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",
}];

Listening for events

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;

Emitting events

Emit events with:

- (void)emit:(NSString *)event, ...;

Selector/Target syntax

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;

Dynamic block invocation

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!");
}];

Credits

The original idea was taken from jerolimov's EventEmitter and expanded to support dynamic block arguments and a single method to emit events.

About

An event emitter implementation for Objective-C with dynamic block invocation based on the node.js EventEmitter API.

Resources

License

Stars

Watchers

Forks

Packages

No packages published