Skip to content

Instantly share code, notes, and snippets.

@tj
Created August 30, 2011 05:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tj/1180283 to your computer and use it in GitHub Desktop.
Save tj/1180283 to your computer and use it in GitHub Desktop.
proxy API for node event emitters (prototype)
var EventEmitter = require('events').EventEmitter;
var request = new EventEmitter;
function Proxy(emitter, callbacks) {
if (!(this instanceof Proxy)) return new Proxy(emitter, callbacks);
var self = this;
// callbacks...
Object.keys(callbacks).forEach(function(event){
emitter.on(event, function(){
// but less slow
var args = [].slice.call(arguments);
// proxy callback
args.push(function(err){
// emit the error or whatever
var args = [].slice.call(arguments, 1);
args.unshift(event);
self.emit.apply(self, args);
});
callbacks[event].apply(null, args);
});
});
// pretend we wildcard error, end, and
// others that do not define a callback
emitter.on('end', function(){
self.emit('end');
});
}
Proxy.prototype.__proto__ = EventEmitter.prototype;
var req = Proxy(request, {
data: function(data, fn){
fn(null, data.toUpperCase());
}
});
req.on('data', function(chunk){
console.log(chunk.toString());
});
req.on('end', function(){
console.log('end');
});
request.emit('data', 'foo');
request.emit('data', 'bar');
request.emit('end');
// FOO
// BAR
// end
// we could maybe add some common shortcuts,
// though I dont think they add much value
Proxy.data = function(emitter, fn){
return Proxy(emitter, { data: fn });
};
var req = Proxy.data(req, function(data, fn){
fn(null, data.toUpperCase());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment