Skip to content

Instantly share code, notes, and snippets.

@boyboi86
Created October 24, 2016 09:41
Show Gist options
  • Save boyboi86/1212d6fb0de4a4595aeedc7dd6e10dce to your computer and use it in GitHub Desktop.
Save boyboi86/1212d6fb0de4a4595aeedc7dd6e10dce to your computer and use it in GitHub Desktop.
Building event emitter in ES6
class EventEmitter {
constructor(){
this.events = {};
}
on(eventName, cb){
if(this.events[eventName]){
this.events[eventName].push(cb);
} else {
this.events[eventName] = [cb];
}
}
emit(eventName, ...rest){
if(this.events[eventName]){
this.events[eventName].forEach(cb => {
cb.apply(null, rest);
})
}
/* Test it */
const ee = new EventEmitter()
ee.on('test', () => {
console.log('EventEmitter works!!')
})
ee.emit('test');
}
}
@boyboi86
Copy link
Author

ES5 version would be as follows:

function EventEmitter(){
  this.events = {};
}

EventEmitter.prototype.on = function(eventName, cb) {
 if(this.events[eventName]) {
  this.events[eventName].push(cb);
 } else {
  this.events[eventName] = [cb];
 }
}

EventEmitter.prototype.emit = function(eventName) {
  if(this.events[eventName]){
  this.events[eventName].forEach((cb) => {
    cb()
  })
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment