Node event emitter in other modules

百般思念 提交于 2019-12-24 11:44:07

问题


I have 3 different javascript files, the smallest one is emitting an event, meanwhile the second (bigger one) file picks up the event and sends it further to the main file. This is what I have tried so far:

//mini.js
var EventEmitter = require('events').EventEmitter;
var ee = new EventEmitter;

console.log("Emitting event");
var message = "Hello world";
ee.emit('testing',message);


//second.js
var mini = require('./mini.js');
var EventEmitter = require('events').EventEmitter;
var ee = new EventEmitter;

mini.on('testing',function(message){
    console.log("Second file received a message:",message);

    console.log("Passing further");
    ee.emit('testing',message);
});

//main.js
var sec = require('./second.js');

sec.on('testing',function(message){
    console.log("Main file received the message",message);
});

However, I get

mini.on('testing',function(message){
        ^
TypeError: undefined is not a function

error when executing the file with node.

What am I doing wrong here? Thanks


回答1:


This one should work :

This is the content to put inside first.js :

//first.js
var util = require('util'),
    EventEmitter = require('events');


function First () {
  EventEmitter.call(this)
}
util.inherits(First, EventEmitter);


First.prototype.sendMessage = function (msg) {    
  this.emit('message', {msg:msg});
};


module.exports = First;

This is the content to put inside second.js :

//second.js
var First = require('./first.js');
var firstEvents = new First();

// listen for the 'message event from first.js'
firstEvents.on('message',function(data){
    console.log('recieved data from first.js is : ',data);
});


// to emit message from inside first.js
firstEvents.sendMessage('first message from first.js');

Now run node second.js and you should have the 'message' event fired for you.

You can use this pattern to achieve any level of messaging between modules.

Hope this helps.




回答2:


You're not exporting your EventEmitter instance in mini.js. Add this to mini.js:

module.exports = ee;

You'll also need to add a similar line in second.js if you want to export its EventEmitter instance in order to make it available to main.js.

Another problem you'll run into is that you're emitting testing in mini.js before second.js adds its testing event handler, so it will end up missing that event.



来源:https://stackoverflow.com/questions/36259965/node-event-emitter-in-other-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!