Search code examples
javascriptnode.jseventemitter

Catch event in different module


I've created event in some module inside my node App and I want to catch this event in other module,I try the following which doesnt work

the module which raise the event

EventEmitter = require("events").EventEmitter;

function updatePort(port) {
  ...
  var ee = new EventEmitter();
  ee.emit("AppDef");

}

Now I want in different module to catch this event and to print something to the console

EventEmitter = require("events").EventEmitter;
var ee = new EventEmitter();
ee.on("AppDef", function () {
  console.log('Port is defiend ' + port);
})

I think that the problem is with the new that I did twice but not sure how to overcome this...


Solution

  • The problem is, you are creating two different EventEmitter instances and you are emitting from one instance and listening for the event in the other.

    To fix this, you need to share the same EventEmitter instance between the modules

    Module 1

    var EventEmitter = require("events").EventEmitter;
    var ee = new EventEmitter();
    
    function updatePort(port) {
      ...
      // emit the port as well
      ee.emit("AppDef", port);
    }
    
    // export the EventEmitter instance
    module.exports.ee = ee;
    

    Module 2

    var mod1 = require('./module1');
    
    // Attach the listener on the EventEmitter instance exported by module1
    mod1.ee.on('AppDef', function(port) {
        console.log('Port is defined ' + port);
    });