我正在 firebase 中开发一个类似存在的系统,其布局如下:
firebase {
user1 {
isOnline: true
}
user 2 {
isOnline: true
}
user3 {
isOnline: false
}
}
isOnline 布尔值是我稍后将使用的将在线用户的名称输出到控制台的方法
例如,在上面的例子中,它会说:
user1 is online.
user2 is online.
这是我的代码:
var gameRef = new Firebase("https://xxx.firebaseio.com/");
var userOnline = new Firebase('https://xxx/.info/connected');
userOnline.on('value', function (snapshot) {
if (snapshot.val()) {
gameRef.child(user).update({
isOnline : true
});
}
else {
gameRef.child(user).update({
isOnline : false
});
}
});
// for each user that is online, output to the console
gameRef.forEach(function (snapshot) {
var obj = snapshot.val();
if(obj.isOnline == true) {
console.log(obj.name + " is online.");
}
});
我的 forEach 似乎有问题,我该如何解决这个问题?
谢谢。
你不能forEach
通过参考,但仅通过快照。
// for each user that is online, output to the console
gameRef.on('value', function(function(gamesSnapshot) {
gamesSnapshot.forEach(function (snapshot) {
var obj = snapshot.val();
if(obj.isOnline == true) {
console.log(obj.name + " is online.");
}
}
});
此代码有两个快照变量:
-
gameSnapshot
是父节点中的数据
-
snapshot
是特定玩家的数据
选择
即使您只想与在线玩家打交道,上述方法也会下载所有玩家。在这种情况下,查询 Firebase 以便仅返回在线玩家会更有效。
// for each user that is online, output to the console
var onlinePlayers = gameRef.orderByChild('isOnline').equalTo(true);
onlinePlayers.on('child_added', function(function(snapshot) {
var obj = snapshot.val();
if(obj.isOnline == true) {
console.log(obj.name + " is online.");
}
});
该代码现在监听child_added
事件,因为 Firebase 一次给我们一个玩家喂食。您可能还需要处理child_changed
and child_removed
,将播放器映射到 HTML 元素后。
尽管这会导致更多的代码,但我通常建议使用查询和child_*
事件,因为它们限制了 Firebase 最初和例如在发生事件时向您发送的数据。玩家离线。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)