Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Last active August 29, 2015 13:56
Show Gist options
  • Save jhurliman/8927033 to your computer and use it in GitHub Desktop.
Save jhurliman/8927033 to your computer and use it in GitHub Desktop.
Micro EventEmitter-like library for JS, based on https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js#L12-31 but with method names more closely matching node.js EventEmitter
window.MicroEvent = function() {};
MicroEvent.prototype = {
on: function(event, listener) {
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(listener);
},
removeListener: function(event, listener) {
this._events = this._events || {};
if (event in this._events === false) return;
this._events[event].splice(this._events[event].indexOf(listener), 1);
},
emit: function(event /* , args... */) {
this._events = this._events || {};
if (event in this._events === false) return;
for (var i = 0; i < this._events[event].length; i++)
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
}
};
MicroEvent.inherit = function(destObject) {
var props = ['on', 'removeListener', 'emit'];
for (var i = 0; i < props.length; i++) {
if (typeof destObject === 'function') {
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
} else {
destObject[props[i]] = MicroEvent.prototype[props[i]];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment