javascript 你如何在 node.js 中共享一个 EventEmitter?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10659266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you share an EventEmitter in node.js?
提问by fancy
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!
谢谢!
采纳答案by srquinn
You can pass arguments to require calls thusly:
您可以将参数传递给 require 调用:
var myModule = require('myModule')(Events)
And then in "myModule"
然后在“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.
话虽如此,如果您想共享一个事件发射器,请创建一个发射器对象,然后在 require 调用中传递给您的“文件/模块/脚本”。
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.
虽然正确,但这是一种代码异味,因为您现在将模块紧密耦合在一起。相反,请考虑使用每个模块都需要的集中式事件总线。
回答by Omer Leshem
@srquinn is correct, you should use a shared single instance:
@srquinn 是正确的,您应该使用共享的单个实例:
eventBus.js:
事件总线.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');
回答by Sascha Reuter
Why not use the EventEmitter of the global process object?
为什么不使用全局进程对象的EventEmitter呢?
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.
优点:您可以禁用或完全删除模块(例如跟踪器),而无需删除路线中的所有跟踪代码。我正在为node-trackable做这件事。
Con: I don't now, but please let me know if you see a catch here ;-)
缺点:我现在不知道,但如果你在这里看到一个问题,请告诉我;-)