node.js 另一个源文件中的事件侦听器

node.js event listener in another source file

我正在尝试设计一个场景,在触发特定事件时,我希望一些侦听器执行某些任务。还试图管理 S.R.P 代码,我希望将侦听器放在不同的源文件中。我想知道这是否可以使用事件发射器。事件发射器是否仅适用于单个源文件?

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

我的另一个源文件是

var emitter = require('events').EventEmitter;
var em = new emitter();

//Subscribe FirstEvent
em.on('FirstEvent', function (data) {
    console.log('First subscriber: ' + data);
});

您创建的每个 eventEmitter 对象都是一个新实例,因此从第一个事件触发的事件不会在第二个事件中触发,因此您的问题的答案是 - 不,这是不可能的。 但是,还有其他解决方案:

我认为最好的办法是创建一个集中式公共事件发射器,如下所示:

//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;

但是如果你想让源文件互相 "know" - 你可以这样做:

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

事件监听器和发射器可以在两个不同的文件中。请看下面的一个简单例子:

第一个文件,姑且称之为eventEx.js

 var EventEmitter = require('events').EventEmitter

   var myEmitter = new EventEmitter();

   myEmitter.on('print', (arg) => {
    console.log(arg);
   })

   exports.myEmitter = myEmitter

第二个文件如下:

var emitter = require('./eventEx.js')
var printEmitter = emitter.myEmitter

printEmitter.emit('print', 'how was Dunkirk?')
printEmitter.emit('print', 'Dunkirk was awesome!!')

这就是我在测试中使用的方式。我将它与 Class 语义

一起使用

需要注意的一点是,在发出事件之前始终需要注册一个侦听器,因为当发出一个事件时,它会查找已经注册的一组侦听器,然后在那里发出流。

//emitter.js
// The core module events has EventEmitter class which we are going to make use of
// note that we are not going to use that explicitly but by means of another class

const EventEmitter = require('events');

Class EventEmitterClass extends EventEmitter{
    emitterMethod(){
      this.emit('testEventEmitted', {obj:'testString object'});
    }
}

module.exports = EventEmitterClass; // we export the module with the objectInstance

//listener.js
// now import the emitter.js and we get back a class - EventEmitterClass
const EventEmitterClass = require('./emitter.js');//give the actual path of js
const eventEmitterObj = new EventEmitterClass();

//now it is mandatory to register the listener before we even think of calling the //emitter method
eventEmitterObj.addListener('testEventEmitted', res => {
   console.log('this is the result from the emitted event:', res);
});

//now call the method that emits the event in the class
eventEmitterObj.emitterMethod();

现在运行 listener.js -> node listerner.js

Apologies, if I have explained things way too elaborate