Last active
September 18, 2017 16:52
-
-
Save bjarneo/e5e89d96f0bbdc8a27d3c5342d92c5ec to your computer and use it in GitHub Desktop.
Event emitter in 11 lines of code
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
| const events = {}; | |
| function on(event, callback) { | |
| if (!events[event]) { | |
| events[event] = []; | |
| } | |
| events[event].push(callback); | |
| } | |
| const trigger = (event, data = null) => events[event].forEach(callback => callback(data)); | |
| // Usage: | |
| on('cat-names', console.log); | |
| trigger('cat-names', 'furguson'); | |
| trigger('cat-names', 'mittens'); | |
| trigger('cat-names', 'boots'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment