Last active
December 17, 2015 22:59
-
-
Save polotek/5685641 to your computer and use it in GitHub Desktop.
Simple example of a node event emitter
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
// Grab the EventEmitter constructor. events is a core node module. | |
var Emitter = require('events').EventEmitter; | |
// Our internal function will generate random numbers | |
function randomInt(limit) { | |
return Math.ceil( Math.random() * limit ); | |
} | |
module.exports = function(limit) { | |
if(!(limit && limit > 0)) { | |
throw new Error('Positive integer limit required'); | |
} | |
// create a new event emitter | |
var emitter = new Emitter(); | |
// Create some incremental output for the emitter | |
setInterval(function() { | |
emitter.emit('int', randomInt(limit)); | |
}, 1000); | |
// return a reference to the emitter so others can listen | |
return emitter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be interested to hear your (and others') take on when to extend EventEmitter versus when to instantiate like in the example. The perspective I am asking from is probably somewhat rare; I have only tinkered with server side Node, but am currently using EventEmitter on the client side via Browserify. At the moment, my event dispatching modules are extending via
inherits( MyModule, require( 'events' ).EventEmitter )
whereinherits
is Node'sutil.inherits
.As I understand it, the callbacks will be executed in the context of the emitter, so in my case, MyModule. That said, I don't think I'd want anyone taking advantage of that fact and writing a callback in some other module that uses this to refer to MyModule. So it seems like instantiating might be good for preventing that, and also eliminating the need for
inherits
.Thoughts?