Skip to content

Instantly share code, notes, and snippets.

@polotek
Last active December 17, 2015 22:59
Show Gist options
  • Save polotek/5685641 to your computer and use it in GitHub Desktop.
Save polotek/5685641 to your computer and use it in GitHub Desktop.
Simple example of a node event emitter
// 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;
};
@bclinkinbeard
Copy link

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 ) where inherits is Node's util.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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment