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
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);
}
},
};