简体   繁体   中英

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM