编辑 澄清一下:我有两个问题。 1. 为什么我的节点被覆盖了? 2. 为什么回调显然被递归调用?
我关注 this guide为我的 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);
}
});
当我测试代码时,它向每个玩家“连接”节点写入了数千个 true
。奇怪的是,每个玩家的所有其他 child 都被删除了。为什么会这样?
播放器节点如下所示:
"player1" : {
"name": "Vladimir Putin",
"country": "Russia",
...,
...,
"connections" : {
...
...
}
}
我没有在我的代码中设置“player1”节点,只是它的一个子节点。我 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);
}
});
我发生了以下情况。
1) 第一个客户端连接
2) 第二个客户端连接
3) 两个客户端都断开连接
在我看来,这是期望的结果。因此,请尝试调试用作 newState 的内容,也许您得到的是“未定义”或其他一些固定值。
关于javascript - Firebase 存在系统 : never stops writing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37528417/