Node.js绕过'听众必须是一个功能'错误

时间:2015-06-13 21:27:06

标签: javascript node.js

我正在使用Node.js和steam-node为Steam编写一些机器人(存储在数组中),每个机器人都有自己的帐户和东西。所以,首先,这是我的代码的一部分:

function onLogon(index){
    console.log('[STEAM] Logged in on bot ' + index);
    bots[index].setPersonaState(Steam.EPersonaState.Online);
    /*do other stuff*/
}

for (var i = 0; i < bots.length; i++){ /*Foreach of the bots, assign a loggedOn even listener */
    bots[i].on('loggedOn', onLogon(i));
}

这段代码给了我一个听众必须是一个功能&#39;。现在,我知道这个错误意味着什么,我应该像这样设置事件监听器:

bots[i].on('loggedOn', onLogon);

但这不起作用,因为我需要将一个变量传递给事件。

我可以这样做:

for (var i = 0; i < accounts.length; i++){
    bots[i].on('loggedOn', function() {
        console.log('[STEAM] Logged in on bot ' + i);
        bots[i].setPersonaState(Steam.EPersonaState.Online);
        //...
    });
}

但它也不起作用,因为我通过引用传递,它以这种方式抛出TypeError: Cannot read property 'setPersonaState' of undefined

bots[i].on('loggedOn', (function(index) {
        console.log('[STEAM] Logged in on bot ' + i);
        bots[index].setPersonaState(Steam.EPersonaState.Online);
        //...
    })(i));

这个ALSO不起作用......

有没有办法在我这里做我想做的事情?或者我应该不使用数组?

2 个答案:

答案 0 :(得分:1)

@Aaron的回答可能是要走的路,但作为替代方案,可以使用一个外壳。

function onLogon(bot, index){
    return function() {
        console.log('[STEAM] Logged in on bot ' + index);
        bot.setPersonaState(Steam.EPersonaState.Online);
        /*do other stuff*/
    };
}

for (var i = 0; i < bots.length; i++){ /*Foreach of the bots, assign a loggedOn even listener */
    bots[i].on('loggedOn', onLogon(bots[i], i));
}

或者以@Aaron的答案为基础,将机器人作为函数上下文传递。

function onLogon(index){
    console.log('[STEAM] Logged in on bot ' + index);
    this.setPersonaState(Steam.EPersonaState.Online);
    /*do other stuff*/
}

for (var i = 0; i < bots.length; i++){ /*Foreach of the bots, assign a loggedOn even listener */
    bots[i].on('loggedOn', onLogon.bind(bots[i], i));
}

答案 1 :(得分:0)

运行时

bots[i].on('loggedOn', onLogon(i));

立即调用onLogon,并将结果传递给on。你真正想要的是绑定第一个参数而不调用它,这可以按如下方式完成:

bots[i].on('loggedOn', onLogon.bind(null, i));

null是因为bind的第一个参数是上下文(或this值),我们并不关心。