Created
March 13, 2013 19:48
-
-
Save katanacrimson/5155477 to your computer and use it in GitHub Desktop.
Because data modification in plugins is nicer than just an emit listener. Note: your listeners have to be specifically adapted for plugin.hook() forwarding
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, | |
util = require('util'), | |
async = require('async') | |
function plugin() { | |
EventEmitter.call(this) | |
} | |
util.inherits(plugin, EventEmitter) | |
// A horribly butchered form of EventEmitter.emit, hacked to support data modification & chaining | |
plugin.prototype.hook = function() { | |
var handler, args, listeners, final, type, self = this | |
args = Array.prototype.slice.call(arguments) | |
final = args.pop(), type = args.shift() | |
// check to see if we have a finale...otherwise, derp out. | |
if(typeof final !== 'function') | |
throw new Error('no final handler defined') | |
if (!this._events) | |
this._events = {} | |
handler = this._events[type] | |
if (typeof handler === 'undefined') { | |
done.apply(done, args) | |
return false | |
} else if (typeof handler === 'function') { | |
async.waterfall([ function(done) { handler.apply(self, args.concat(done)) } ], final) | |
} else if (typeof handler === 'object') { | |
listeners = handler.slice() | |
listeners[0].bind.apply(listeners[0], args) // easy solution to prepend the initial args into the first listener call | |
async.waterfall(listeners, final) | |
} | |
return true | |
} | |
module.exports = new plugin() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment