我正在使用peer.js并尝试将所有传入连接存储在一个数组中。
应用程序背景:计算机充当主控台。电话使用控制台对等ID连接到控制台,并向控制台发送它的对等ID。然后,控制台读入每个对等ID并与其创建数据连接
我正在尝试将连接存储在一个数组中,然后我可以在我需要的任何函数中调用连接。当我尝试将连接传递给函数' SendPhonePlayerDetails'连接打印为未定义。
//establish a connection
//data.pid is the peer id of the phone
connections[current_player] = peer.connect(data.pid);
setTimeout(function() {
sendPhonePlayerDetails(connections[current_player]);
},'2000');
function sendPhonePlayerDetails(connection)
{
console.log(connection) //prints undefined;
player_num = Object.size(players); //get the player number
player_name = players["p" + player_num][1] //get the players name
//send data to the phone
setTimeout(function() {
send_data({player_number: player_num, player_name: player_name }, connection);
},'2000');
//if not player 1 notify them who is the leader
if(player_num > 1){
setTimeout(function() {
send_data({controlling: players["p1"][1] }, connection);
},'2000');
}
}
function send_data(data, connection)
{
if (!connection) return;
connection.send(data); //send the data to the phone
}
答案 0 :(得分:0)
连接数组未被解释为全局。通过添加'window。',我能够控制日志并传递连接数组。
setTimeout(function() {
sendPhonePlayerDetails(window.connections['p' + (current_player-1)]);
},'2000');