【问题标题】:Firebase listen for changes in particular fieldFirebase 监听特定领域的变化
【发布时间】:2013-09-18 15:23:10
【问题描述】:

我正在使用 Firebase 进行聊天的实时虚拟房间。我想知道是否可以监听 firebase db 中特定字段的更新。例如,如果数据的结构如下:

{channel_name: test-app,
  {id: unique_id_generated_automatically_by_firebase,
    {user_id: some_id,
     position: {
       current: {x:x,y:y},
       start: {x:x,y:y},
       end: {x:x,y:y}
    }
  }
  {id: unique_id_generated_automatically_by_firebase,
    {user_id: some_id,
     position: {
       current: {x:x,y:y},
       start: {x:x,y:y},
       end: {x:x,y:y}
    }
  }
} 

目前我能够像这样监听 db 中的任何变化

//reference to firebase db
var room = new Firebase("https://test-app.firebaseio.com/");
room.on("child_changed", function(snapshot) {
   //do something here; 
});

我正在寻找一种方法来监听字段 position.start 和 position.end 的变化,但忽略 position.current(这些是唯一会更新的字段)。只有在用户登录时才需要当前位置,以获取当前房间内所有用户的当前位置。之后,位置将根据开始和结束值在客户端计算机上进行动画处理。我还想通过不向所有连接的客户端发送当前位置的更改来节省数据传输,但在请求时具有当前状态。非常感谢任何帮助和建议。

【问题讨论】:

    标签: firebase


    【解决方案1】:

    您可以为您感兴趣的每个字段绑定一个 .on("value") 事件。

    var room = new Firebase("https://test-app.firebaseio.com/" + roomID);
    room.child("position/start").on("value", onChange);
    room.child("position/end").on("value", onChange);
    function onChange(snapshot) {
      if (snapshot.name() == "start") {
        // position.start changed to snapshot.val()
      } else if (snapshot.name() == "end") {
        // position.end changed to snapshot.val()
      }
    }
    

    【讨论】:

    • 不幸的是没有用。我认为这是因为每个位置对象都由唯一的 id 对象包装,所以引用将是 room.child(unique_id/position/end).on... 我找到了类似问题的另一个答案,建议在“child_added”函数中单独附加侦听器:room.on("child_added", function(snapshot){ snapshot.ref().child("position/end").on()})
    • 我遇到的另一个问题是从快照的父级检索数据。因为事件仅附加到开始/结束字段的更改,快照对象仅包含这些字段的子项?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2017-04-19
    • 2023-03-27
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多