使用提供的回调参数在Node.js中监听事件。

huangapple go评论57阅读模式
英文:

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(&#39;ws-price&#39;, 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(&#39;../services/events&#39;)

module.exports = {
  run: async (bot) =&gt; {
    Events.on(&#39;ws-price&#39;, callback(event, bot)) // &lt;--- pass &quot;bot&quot; variable
  },

  stop: async (bot) =&gt; {
    Events.off(&#39;ws-price&#39;, callback(event, bot)) // &lt;--- pass &quot;bot&quot; variable
  }
}

const callback = (event, bot) =&gt; {
  console.log(bot?.id, event) // How to access &quot;bot&quot; here ?
}

I get an error: ReferenceError: event is not defined

答案1

得分: 2

您需要创建一个封闭bot的包装函数,当它被调用时,将使用它接收的botevent来调用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) =&gt; {
        const cb = (event) =&gt; callback(event, bot);
        callbacks.set(bot, cb);
        Events.on(&quot;ws-price&quot;, cb);
    },

    stop: async (bot) =&gt; {
        const cb = callbacks.get(bot);
        if (cb) {
            callbacks.delete(bot);
            Events.off(&quot;ws-price&quot;, cb);
        }
    },
};

huangapple
  • 本文由 发表于 2023年3月31日 20:11:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定