简体   繁体   English

如何避免事件监听器共享 Scope

[英]How To Avoid Event Listeners Shared Scope

I'm making a bot for a game to move to a block and mine it by listening for events and I noticed something weird when trying to run async functions in a event listener.我正在为游戏制作一个机器人来移动到一个块并通过侦听事件来挖掘它,我在尝试在事件侦听器中运行异步函数时发现了一些奇怪的东西。 When the aysnc function finishes it runs a call back function using a variable that is declared in the second event listener called pos but once the function is called the event has already happened again.当 aysnc function 完成时,它使用在第二个事件侦听器中声明的名为 pos 的变量运行回调 function 但一旦 ZC1C425268E68385D1AB5074C17A94F1 再次发生,该事件已被调用。 The call back function uses the new value from the event from the first listener instead of the old value from when the async function was called in the second listener.回调 function 使用来自第一个侦听器的事件的新值,而不是在第二个侦听器中调用异步 function 时的旧值。 I was wondering how I could avoid this problem.我想知道如何避免这个问题。

This the first event listener:这是第一个事件监听器:

bot.client.on('block_change', packet => {
    let id = packet.type
    let loc = packet.location;
    let pos = new Vec3(Math.floor(loc.x), Math.floor(loc.y), Math.floor(loc.z))
    let block = new Block(Math.floor(id / 16), 5, id % 16)
    setBlock(pos, block);
});

This the second listener:这是第二个听众:

bot.client.on('block_change', (packet) => {
    loc = packet.location
    block = new Block(Math.floor(packet.type/16),0,packet.type%16)
    pos = new Vec3(loc.x,loc.y,loc.z)
    if (packet.type === 16) {
        bot.navigate.to(pos,{endRadius:3, onArrived: ()=>{bot.dig(pos)}});
    }
});

both listeners need to use the keyword "let" or "const" to change the global variables eg两个侦听器都需要使用关键字“let”或“const”来更改全局变量,例如

bot.client.on('block_change', (packet) => {
    let loc = packet.location
    let block = new Block(Math.floor(packet.type/16),0,packet.type%16)
    let pos = new Vec3(loc.x,loc.y,loc.z)
    if (packet.type === 16) {
        bot.navigate.to(pos,{endRadius:3, onArrived: ()=>{bot.dig(pos)}});
    }
});

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

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