Created
February 12, 2016 05:49
-
-
Save thomassuckow/efdf79aadb344b5e2dac to your computer and use it in GitHub Desktop.
A basic event emitter
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
import _ from 'lodash'; | |
const events = Symbol('Events'); | |
export default class EventEmitter { | |
constructor() { | |
this[events] = {}; | |
} | |
on(event, fn) { | |
const listeners = this[events][event] = this[events][event] || []; | |
if( !_.includes(listeners, fn) ) { | |
listeners.push(fn); | |
} | |
return this; | |
} | |
off(event, fn) { | |
this[events][event] = _.without(this[events][event],fn); | |
return this; | |
} | |
emit(event, ...args) { | |
const listeners = this[events][event] || []; | |
for(let listener of listeners) { | |
listener.apply(this,args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment