我正确使用ForEach吗?

Not*_*rag 3 firebase

我正在使用以下布局在firebase中创建类似于状态的系统:

firebase {
   user1 {
     isOnline: true
   }
   user 2 {
     isOnline: true
   }
   user3 {
     isOnline: false
   }
}
Run Code Online (Sandbox Code Playgroud)

isOnline booleans是我稍后将用于输出在线用户名到控制台的内容

例如,在上面的情况下,它会说:

user1 is online.
user2 is online.
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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.");
            }
        }); 
Run Code Online (Sandbox Code Playgroud)

我的forEach似乎有问题,我该如何解决这个问题?谢谢.

Fra*_*len 13

您不能通过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.");
           }
       }
   }); 
Run Code Online (Sandbox Code Playgroud)

此代码有两个快照变量:

  • 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.");
       }
   }); 
Run Code Online (Sandbox Code Playgroud)

该代码现在可以监听该child_added事件,因为Firebase会一次一个地向玩家提供勺子.你可能还必须处理child_changedchild_removed,一旦玩家映射到HTML元素.

即使这会产生更多代码,我通常会建议使用查询和child_*事件,因为它们会限制Firebase最初发送给您的数据以及播放器脱机时的数据.