user2066880
user2066880

Reputation: 5034

Node.js events applications

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.

Upvotes: 0

Views: 74

Answers (1)

Gena Moroz
Gena Moroz

Reputation: 954

If you want to use crossmodule you should export your class, and create it's intance externally. eg

 module.exports = SimpleEE

outside

SimpleEE =  require("yourModule")
var instance  = new SimpleEE()
instance.on("valChanged",function(){})
instance.changeVal("22");

or create a singleTone so you export created instance

 module.exports = new SimpleEE()

external

SimpleEE =  require("yourModule")

SimpleEE.on("valChanged",function(){})
SimpleEE.changeVal("22");

you can loog here How do you share an EventEmitter in node.js? to get info about triggering and listening to GLOBAL events

Upvotes: 1

Related Questions