Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Created November 17, 2016 20:58
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 carlosascari/7f79c081a49f64032424366fdbbf7521 to your computer and use it in GitHub Desktop.
Save carlosascari/7f79c081a49f64032424366fdbbf7521 to your computer and use it in GitHub Desktop.
EventEmiter es6 class intented to extend existing classes
class EventEmitter {
constructor() {
this.cbs = {};
}
on(evt, cb) {
if (evt && typeof cb === 'function') {
if (!this.cbs[evt]) {
this.cbs[evt] = [];
}
this.cbs[evt].push(cb);
}
}
emit(evt) {
const cbs = this.cbs[evt];
if (cbs && cbs.length) {
const args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
const cb = cbs[i];
cb.apply(cb, args);
}
}
}
off(evt, cb) {
if (evt) {
if (typeof cb === 'function') {
const i = this.cbs[evt].indexOf(cb);
if (i !== -1) {
this.cbs[evt].splice(i, 1);
}
} else {
this.cbs[evt] = [];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment