你如何在node.js中共享EventEmitter? [英] How do you share an EventEmitter in node.js?
问题描述
我想从一个文件/模块/脚本中发出事件,并在另一个文件/模块/脚本中侦听它们。如何在不污染全局命名空间的情况下在它们之间共享发射器变量?
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?
谢谢!
推荐答案
您可以将参数传递给require调用:
You can pass arguments to require calls thusly:
var myModule = require('myModule')(Events)
然后在myModule中
And then in "myModule"
module.exports = function(Events) {
// Set up Event listeners here
}
话虽如此,如果你想共享一个事件发射器,创建一个发射器对象,然后在require调用中传递给你的文件/模块/脚本。
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.
虽然正确,但这是代码味道,因为您现在将模块紧密耦合在一起。相反,请考虑使用每个模块中可能需要的集中式事件总线。
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.
这篇关于你如何在node.js中共享EventEmitter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!