Skip to content

Instantly share code, notes, and snippets.

@othiym23
Created October 1, 2013 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save othiym23/6774425 to your computer and use it in GitHub Desktop.
Save othiym23/6774425 to your computer and use it in GitHub Desktop.
Namespace.prototype.bindEmitter = function (source) {
assert.ok(source.on && source.addListener && source.emit, "can only bind real EEs");
var namespace = this;
var contextName = '__' + this.name;
function capturer(on) {
return function (event, listener) {
listener[contextName] = namespace.active;
var returned = on.call(this, event, listener);
// what in the seven hells is ReadableStream doing here?
wrap(this, 'on', capturer);
wrap(this, 'addListener', capturer);
return returned;
};
}
function prepare(handlers) {
var replacements = [];
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i];
if (handler[contextName]) {
replacements.push(namespace.bind(handler, handler[contextName]));
}
else {
replacements.push(handler);
}
}
return replacements;
}
function puncher(emit) {
return function (event) {
if (!this._events[event]) return emit.apply(this, arguments);
// setup
var events = this._events[event];
if (typeof events === 'function' && events[contextName]) {
this._events[event] = namespace.bind(events, events[contextName]);
}
else if (events.length) {
this._events[event] = prepare(events);
}
// application
var returned = emit.apply(this, arguments);
this._events[event] = events;
return returned;
};
}
wrap(source, 'addListener', capturer);
wrap(source, 'on', capturer);
wrap(source, 'emit', puncher);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment