Created
August 13, 2019 19:14
-
-
Save bitmage/4a3d262373e0336e1aad0ffd5f86366b to your computer and use it in GitHub Desktop.
event emitters example
This file contains 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 {EventEmitter} = require('events') | |
// initialization | |
const ee = new EventEmitter() | |
ee.isReady = false | |
ee.on('ready', function() {ee.isReady = true}) | |
ee.onReady = function(cb) { | |
if (this.isReady) { | |
// call immediately | |
cb() | |
} else { | |
// attach a handler | |
this.once('ready', cb) | |
} | |
} | |
// ... some time passes | |
// has ready been emitted? then trigger immediately! otherwise wait for it | |
ee.onReady(() => console.log('ready!')) | |
// in the future | |
ee.emit('ready') | |
// should also be called | |
ee.onReady(() => console.log('still ready?')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment