hel*_*ght 10 javascript firebase
编辑澄清:我有两个问题.1.为什么我的节点被覆盖了?2.为什么回调显然被称为recursivly?
我按照本指南为我的webapp实现了状态系统.我希望所有登录用户始终能够知道所有其他用户是否在线.这是我的代码:
currentGameRef = gamesInProgressRef.child(newState.currentTable);
var myConnectionsRef = currentGameRef.child("player" + newState.myPlayerNumber).child("connections");
var lastOnlineRef = currentGameRef.child("player" + newState.myPlayerNumber).child("lastOnline");
var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on("value", function(snap) {
if(snap.val() == true){
var con = myConnectionsRef.push(true);
con.onDisconnect().remove();
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
}
});
Run Code Online (Sandbox Code Playgroud)
当我测试代码时,它会true
向每个玩家"连接" - 节点写入数千个代码.奇怪的是,每个玩家的所有其他孩子都被删除了.为什么会这样?播放器节点如下所示:
"player1" : {
"name": "Vladimir Putin",
"country": "Russia",
...,
...,
"connections" : {
...
...
}
}
Run Code Online (Sandbox Code Playgroud)
我没有在我的代码中设置"player1"-node,只是它的一个孩子.我知道100%的上述代码导致了这种行为,但我无法弄清楚原因.有人可以告诉我为什么上面的代码清除播放器节点?
看来newState自带的变量出了问题。我在这里做了这个测试:
// Initialize Firebase
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
// fixed values just for test
var newState = {
myPlayerNumber: 1,
currentTable: 2
};
var gamesInProgressRef = firebase.database().ref('games');
currentGameRef = gamesInProgressRef.child(newState.currentTable);
var myConnectionsRef = currentGameRef.child("player" + newState.myPlayerNumber).child("connections");
var lastOnlineRef = currentGameRef.child("player" + newState.myPlayerNumber).child("lastOnline");
var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on("value", function(snap) {
if(snap.val() == true){
var con = myConnectionsRef.push(true);
con.onDisconnect().remove();
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
}
});
Run Code Online (Sandbox Code Playgroud)
我发生了以下情况。
1)第一个客户端连接
2)第二个客户端连接
3)两个客户端均已断开连接
在我看来,这就是想要的结果。因此,请尝试调试用作 newState 的内容,也许您会得到“未定义”或其他一些固定值。
归档时间: |
|
查看次数: |
335 次 |
最近记录: |