Example use of EventEmitter in Node.js
Here is an example of how to use the EventEmitter object in node.js …
var EventEmitter = require('events').EventEmitter; var ee = new EventEmitter; ee.on('someevent', function() { console.log('The someevent happened'); }); // emit the event ee.emit('someevent'); // emit the event again ee.emit('someevent');
The output will be …
The someevent happened
The someevent happened
But if you use the “once” instead of “on” as in …
var EventEmitter = require('events').EventEmitter; var ee = new EventEmitter; ee.once('someevent', function() { console.log('The someevent happened'); }); // emit the event ee.emit('someevent'); // emit the event again ee.emit('someevent');
The output will just be …
The someevent happened
because the event handler is invoked only once.