Skip to content Skip to sidebar Skip to footer

Node Event Emitter In Other Modules

I have 3 different javascript files, the smallest one is emitting an event, meanwhile the second (bigger one) file picks up the event and sends it further to the main file. This i

Solution 1:

You're not exporting your EventEmitter instance in mini.js. Add this to mini.js:

module.exports = ee;

You'll also need to add a similar line in second.js if you want to export its EventEmitter instance in order to make it available to main.js.

Another problem you'll run into is that you're emitting testing in mini.js before second.js adds its testing event handler, so it will end up missing that event.

Solution 2:

This one should work :

This is the content to put inside first.js :

//first.jsvar util = require('util'),
    EventEmitter = require('events');


functionFirst () {
  EventEmitter.call(this)
}
util.inherits(First, EventEmitter);


First.prototype.sendMessage = function (msg) {    
  this.emit('message', {msg:msg});
};


module.exports = First;

This is the content to put inside second.js :

//second.jsvarFirst = require('./first.js');
var firstEvents = newFirst();

// listen for the 'message event from first.js'
firstEvents.on('message',function(data){
    console.log('recieved data from first.js is : ',data);
});


// to emit message from inside first.js
firstEvents.sendMessage('first message from first.js');

Now runnode second.js and you should have the 'message' event fired for you.

You can use this pattern to achieve any level of messaging between modules.

Hope this helps.

Post a Comment for "Node Event Emitter In Other Modules"