Created
August 30, 2011 05:58
-
-
Save tj/1180283 to your computer and use it in GitHub Desktop.
proxy API for node event emitters (prototype)
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
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