Saturday, March 02, 2013

Coordinating Nodejs Events EventAggregator

Been looking for a quick way to synchronize multiple events and callbacks. Looked around and found a few solutions but nothing exactly what I was looking for.

Henceforth, wrote up a quick module called EventAggregator.

npm install event-aggregator

So here's the problem.  There's multiple resources we're waiting for these asynchronous operations to complete.  Since we're looking to avoid nesting the code several levels deep inside of some functions, what we'll do is subscribe to several events and execute the necessary actions when they've completed.

EventAggregator allows management of several triggering events each with their own lists.  Multiple triggers can be set up by passing an array instead of a string for the triggering event.

Load the module:

var EventAggregator = require('event-aggregator').EventAggregator;

Subscribe to the events:

var aggregator = new EventAggregator(); 

// Resource 1 
aggregator.waitEvent('complete', resource1, 'ready'); 
aggregator.waitEvent('complete', resource1, 'connect'); 

// Resource 2 
resource2.createConnection(aggregator.waitCallback('complete'));

Set up a listener.

aggregator.on('complete', function() { // ... });

It's up on npm (https://npmjs.org/package/event-aggregator). It's also up on git (https://github.com/henrytseng/event-aggregator).

No comments: