Skip to content

Instantly share code, notes, and snippets.

@schmty
Last active August 29, 2015 14:16
Show Gist options
  • Save schmty/550dc8285b26c5b3057f to your computer and use it in GitHub Desktop.
Save schmty/550dc8285b26c5b3057f to your computer and use it in GitHub Desktop.
basic event emitter implementation for practice
function EventEmitter() {
this._events = {};
}
EventEmitter.prototype.on = function(event, func) {
if (!this._events[event] || this._events === {}) {
this._events[event] = func;
} else if (this._events[event] && !(this._events[event] instanceof Array)) {
var firstFunc = this._events[event];
this._events[event] = [];
this._events[event].push(firstFunc);
this._events[event].push(func);
} else if (this._events[event] && this._events instanceof Array) {
this._events[event].push(func);
}
};
EventEmitter.prototype.emit = function(event) {
if (this._events[event] instanceof Array) {
var eventArr = this._events[event];
for (var i = 0; i < eventArr.length; i++) {
var func = eventArr[i];
func();
}
} else if (this._events[event] && !(this._events[event] instanceof Array)) {
var firefunc = this._events[event];
firefunc();
}
};
EventEmitter.prototype.off = function(event) {
delete this._events[event];
};
emitter = new EventEmitter();
emitter.on('hello', function() {
console.log('hello fired!');
});
emitter.on('hello', function() {
console.log('hola');
});
emitter.on('goodbye', function() {
console.log('goodbye fired');
});
emitter.emit('hello');
emitter.emit('goodbye');
console.log(emitter._events.hello);
console.log(emitter._events.goodbye);
emitter.off('hello');
emitter.off('goodbye');
console.log(emitter._events.hello);
console.log(emitter._events.goodbye);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment