我在其他地方调用了scoreBoard(),它在函数内部运行了console.log,但是它没有进一步到下一个函数?任何人都可以给我一些见解,为什么这是?因为我只想调用这个socket.on或者至少在玩家登录时绘制表格。
var scoreBoard = function(){
console.log('Gets into here, does not go into the next function');
socket.on('allScores', function(data){
console.log('inside');
var playerScores = data;
// console.log(playerScores);
document.write('<table>');
document.write('<tr> <th>Player</th> <th>Score</th> </tr>');
for(var i = 0; i < playerScores.length; i++)
{
document.write('<tr><td>' + playerScores[i].username + '</td><td>' + playerScores[i].score + '</td></tr>');
}
document.write('</table>');
})
}
这没有运行
console.log('inside');
答案 0 :(得分:1)
因为console.log('inside');
位于事件侦听器中。它不在上一次console.log
调用后按顺序执行的函数内。
如果您确定正在生成事件,那么它仅在调用scoreBoard()
函数之前生成。由于您只是在该函数中附加事件侦听器,因此只有在您运行allScores
后才开始侦听scoreBoard()
事件。
解决方案是将socket.on('allScores', function(data){ ... })
部分移到scoreBoard()
函数体之外。