Search code examples
node.jseventemitter

Nodejs: use eventEmitter object globally


Lets say I have 3 exposed functions: user, posts, articles

all of which needs to emit messages to a file called mediator where all of the events are set.

Currently I'm have trouble doing so

In the mediator file i have something like so:

var EventEmitter = require('events').EventEmitter;
  , pubsub = new EventEmitter();

exports.pubsub = new EventEmitter()

pubsub.on('loggedIn', function(msg) {
    console.log(msg);
});

and in the user, post and article functions. Something like so:

var mediator = require('../config/mediator')
    , _ = require('underscore')

exports.account = function(req, res) {
  var returned = _.omit(req.user._doc, 'password' )

  mediator.pubsub.emit('loggedIn', 'A User logged in');

  res.send(returned);
};

The emit is getting completely ignored, no error or anything. Not sure if I'm doing it right so any direction would be appreciated. The desired return is work as expected though.


Solution

  • You're instantiating the EventEmitter twice, so the exported one is not the one that subscribes to the event. This works:

    var EventEmitter = require('events').EventEmitter
      , pubsub = new EventEmitter();
    
    exports.pubsub = pubsub;
    
    pubsub.on('loggedIn', function(msg) {
        console.log(msg);
    });