Skip to content

Instantly share code, notes, and snippets.

@nicokaiser
Created February 19, 2018 14:49
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 nicokaiser/3955fc2d6dbb1d4def702cb7d680c507 to your computer and use it in GitHub Desktop.
Save nicokaiser/3955fc2d6dbb1d4def702cb7d680c507 to your computer and use it in GitHub Desktop.
function EventEmitter() {
this._events = {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
EventEmitter.prototype.emit = function(type) {
if (!this._events[type]) return false;
var args = Array.prototype.slice.call(arguments, 1);
var listeners = this._events[type].slice();
for (var i = 0; i < listeners.length; i++)
listeners[i].apply(this, args);
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
if (!this._events[type])
this._events[type] = [listener];
else
this._events[type].push(listener);
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
EventEmitter.prototype.removeListener = function(type, listener) {
if (!this._events[type])
return this;
var list = this._events[type];
var position = -1;
for (var i = list.length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
if (!this._events)
return this;
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment