Last active
February 26, 2019 15:21
-
-
Save artemgurzhii/352f59a5ff6b050f4f6e22cb0fef0324 to your computer and use it in GitHub Desktop.
Event Emitter
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(event, func) { | |
if(this.events[event]) { | |
this.events[event].push(func); | |
} else { | |
this.events[event] = [func]; | |
} | |
} | |
trigger(event, ...rest) { | |
if(this.events[event]) { | |
this.events[event].forEach(func => { | |
func.apply(rest); | |
}); | |
} | |
} | |
} | |
const ee = new EventEmitter(); | |
ee.on('click', () => { | |
console.log('Click event was triggered'); | |
}); | |
ee.trigger('click'); // returns 'Click event was triggered' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment