Created
November 17, 2016 20:58
-
-
Save carlosascari/7f79c081a49f64032424366fdbbf7521 to your computer and use it in GitHub Desktop.
EventEmiter es6 class intented to extend existing classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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