英文:
Listening to events with a provided callback param in node.js
问题
以下是代码部分的翻译:
const Events = require('../services/events')
module.exports = {
run: async (bot) => {
Events.on('ws-price', callback(event, bot)) // <--- 传递 "bot" 变量
},
stop: async (bot) => {
Events.off('ws-price', callback(event, bot)) // <--- 传递 "bot" 变量
}
}
const callback = (event, bot) => {
console.log(bot?.id, event) // 如何在这里访问 "bot"?
}
出现错误:ReferenceError: event is not defined
英文:
My node.js server is connected to a websocket. It continuosly sends the Events.emit('ws-price', data)
:
From another part of the js file, we can start and stop listening for those events. To be able to removeListener - same callback function should be used for both Events.on
and Events.off
.
How would I access a provided "bot" param in "run" and "stop" functions within the callback method ?
const Events = require('../services/events')
module.exports = {
run: async (bot) => {
Events.on('ws-price', callback(event, bot)) // <--- pass "bot" variable
},
stop: async (bot) => {
Events.off('ws-price', callback(event, bot)) // <--- pass "bot" variable
}
}
const callback = (event, bot) => {
console.log(bot?.id, event) // How to access "bot" here ?
}
I get an error: ReferenceError: event is not defined
答案1
得分: 2
您需要创建一个封闭bot
的包装函数,当它被调用时,将使用它接收的bot
和event
来调用callback
函数。然后,请记住这个函数,以便在调用stop
时将其删除(可以使用Map
来实现这一点):
// 当前回调函数的映射(已经`run`但未`stop`)
const callbacks = new Map();
module.exports = {
run: async (bot) => {
const cb = (event) => callback(event, bot);
callbacks.set(bot, cb);
Events.on("ws-price", cb);
},
stop: async (bot) => {
const cb = callbacks.get(bot);
if (cb) {
callbacks.delete(bot);
Events.off("ws-price", cb);
}
},
};
英文:
You'll have to create a wrapper function that closes over bot
that, when it's called, calls callback
with both the bot
and the event
it receives. Then remember that function so you can remove it when stop
is called (a Map
is good for that):
// A map of the current callbacks (have been `run` and not `stop`ped)
const callbacks = new Map();
module.exports = {
run: async (bot) => {
const cb = (event) => callback(event, bot);
callbacks.set(bot, cb);
Events.on("ws-price", cb);
},
stop: async (bot) => {
const cb = callbacks.get(bot);
if (cb) {
callbacks.delete(bot);
Events.off("ws-price", cb);
}
},
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论