我的node.js服务器连接到一个websocket。连续发送Events.emit('ws-price', data)
:
从js文件的另一部分,我们可以开始和停止侦听这些事件。为了能够removeListener -相同的回调函数应该用于Events.on
和Events.off
。
如何访问提供的"bot"run"中的参数和";stop"回调方法中的函数?
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 ?
}
我得到一个错误:ReferenceError: event is not defined
您必须创建一个关闭在bot
之上的包装器函数,当它被调用时,用它接收到的bot
和event
调用callback
。然后记住该函数,以便在调用stop
时删除它(Map
很好):
// 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);
}
},
};