How do you share an EventEmitter in node.js?

霸气de小男生 提交于 2019-12-18 12:49:16

问题


I want to emit events from one file/module/script and listen to them in another file/module/script. How can I share the emitter variable between them without polluting the global namespace?

Thanks!


回答1:


You can pass arguments to require calls thusly:

var myModule = require('myModule')(Events)

And then in "myModule"

module.exports = function(Events) {
    // Set up Event listeners here
}

With that said, if you want to share an event emitter, create an emitter object and then pass to your "file/module/script" in a require call.

Update:

Though correct, this is a code smell as you are now tightly coupling the modules together. Instead, consider using a centralized event bus that can be required into each module.




回答2:


@srquinn is correct, you should use a shared single instance:

eventBus.js:

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('uncaughtException', function (err) {
    console.error(err);
});

module.exports = emitter;

Usage:

var bus = require('../path/to/eventBus');

// Register event listener
bus.on('eventName', function () {
    console.log('triggered!');
});

// Trigger the event somewhere else
bus.emit('eventName');



回答3:


Why not use the EventEmitter of the global process object?

process.on('customEvent', function(data) {
  ...
});

process.emit('customEvent', data);

Pro: You can disable or completely remove a module (for instance a tracker), without removing all your tracking code within your routes. I'm doing exactly that for node-trackable.

Con: I don't now, but please let me know if you see a catch here ;-)



来源:https://stackoverflow.com/questions/10659266/how-do-you-share-an-eventemitter-in-node-js

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