I am trying to design a scenario where on a particular event getting triggered, I wanted a few listeners to perform some task. Trying to also manage S.R.P of code, I want to have the listeners in a different source file. I want to know if this is possible using event Emitter. Does event emitter only work on a single source file?
var events = require('events');
var em = new events.EventEmitter();
exports.saveScheme = function (req, res) {
var dal = dalFactory.createDAL(constants.SCHEME);
return new Promise.resolve(dal.PromiseSave(req.body))
.then(function(data){
var schemeId = data._id;
em.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
em.emit('FirstEvent', 'Test event emitter');
}).catch(function(error){
console.log(error);
});
};
My other source file is
var emitter = require('events').EventEmitter;
var em = new emitter();
//Subscribe FirstEvent
em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
Every eventEmitter object you create is a new instance so events fired from the first one won't be triggered in the second, so the answer to your question is - no, it's not possible. However, there are other solutions:
I think the best one is to create a centralized common eventEmitter, like so:
//firstFile.js
var common = require('./common');
var commonEmitter = common.commonEmitter;
exports.saveScheme = function (req, res) {
var dal = dalFactory.createDAL(constants.SCHEME);
return new Promise.resolve(dal.PromiseSave(req.body))
.then(function(data){
var schemeId = data._id;
commonEmitter.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
commonEmitter.emit('FirstEvent', 'Test event emitter');
}).catch(function(error){
console.log(error);
});
};
//secondFile.js
var common = require('./common');
var commonEmitter = common.commonEmitter;
//Subscribe FirstEvent
commonEmitter.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
//common.js
var events = require('events');
var em = new events.EventEmitter();
module.exports.commonEmitter = em;
But if you want the source file to "know" each other - You can do something like this:
//firstFile.js
var events = require('events');
var em = new events.EventEmitter();
exports.saveScheme = function (req, res) {
var dal = dalFactory.createDAL(constants.SCHEME);
return new Promise.resolve(dal.PromiseSave(req.body))
.then(function(data){
var schemeId = data._id;
em.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
em.emit('FirstEvent', 'Test event emitter');
}).catch(function(error){
console.log(error);
});
};
exports.emitter = em;
//secondFile.js
var firstFile = require('./firstFile');
var firstFileEmitter = firstFile.emitter;
//Subscribe FirstEvent
firstFileEmitter.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});