I'm having a little trouble understanding the applications of events in Node.js. Consider the following standard custom EventEmitter implementation:
var EventEmitter = require('events').EventEmitter;
var util = require('util');
function SimpleEE() {
var self = this;
self.val = false;
EventEmitter.call(this);
}
util.inherits(SimpleEE, EventEmitter);
SimpleEE.prototype.changeVal = function() {
self.val = !self.val;
self.emit('valChanged', self.val);
}
SimpleEE.on('valChanged', function(newVal) {
console.log('val was changed to ' + newVal);
});
In this case, I don't see the point of having the listener. Assuming, you want the same action to take place everytime the event occurs, why wouldn't you put the listener's callback function in place of the emit()
call?
The reason this is confusing to me is because I originally thought events were meant for cross-module communication; i.e. one module would be alerted when an appropriate action occurs in another module. However, from my understanding, the emitter and the listener have to be registered under the same EventEmitter instance in order to work.
Thanks for helping me understand.