Skip to content

Instantly share code, notes, and snippets.

@thomassuckow
Created February 12, 2016 05:49
Show Gist options
  • Save thomassuckow/efdf79aadb344b5e2dac to your computer and use it in GitHub Desktop.
Save thomassuckow/efdf79aadb344b5e2dac to your computer and use it in GitHub Desktop.
A basic event emitter
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