Created
October 24, 2016 09:41
-
-
Save boyboi86/1212d6fb0de4a4595aeedc7dd6e10dce to your computer and use it in GitHub Desktop.
Building event emitter in ES6
This file contains hidden or 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.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'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ES5 version would be as follows: