简体   繁体   English

在 node.js 中的两个 javascript 文件之间发送和接收事件

[英]Send and receive events between two javascript files in node.js

I am trying to communicate between two javascript files using EventEmitter, but I am struggling to get it working in both directions.我正在尝试使用 EventEmitter 在两个 javascript 文件之间进行通信,但我正在努力让它在两个方向上工作。

I have server.js:我有 server.js:

let api = require('./api')

// Does not work
api.on("yo", data => {
    console.log(data)
})

// Works
api.emit("ready", "Server ready") 

and api.js:和 api.js:

const EventEmitter = require('events')
let api = new EventEmitter()

// Works
api.on("ready", data => {
    console.log(data)
})

// Does not work
api.emit("yo", "yo yo")

module.exports = api

server.js is able to emit events to api.js , but not the other way around. server.js能够向api.js发出事件,但api.js不行。 I have tried module.exports and requiring both files in each other respectively at the same time, but that is causing errors.我已经尝试过 module.exports 并同时分别要求两个文件,但这会导致错误。

How can I accomplish two-way emits/ons between these two files?如何在这两个文件之间完成双向发射/打开?

At first api.js is initialized and at that moment nobody is subscribed on 'yo' event yet.首先 api.js 被初始化,此时还没有人订阅 'yo' 事件。 So you shouldn't emit any events during any module initialization at all.所以你根本不应该在任何模块初始化期间发出任何事件。 Try to emit events afterwards somehow.之后尝试以某种方式发出事件。

OR you can move all subscribing stuff into another module in which you can emit any event after all subscriptions are done.或者您可以将所有订阅内容移动到另一个模块中,您可以在所有订阅完成后在其中发出任何事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM