注册Firebase Listener而不调用它

Register Firebase Listener Without Calling It?

本文关键字:调用 Firebase Listener 注册      更新时间:2023-09-26

是否可以在注册Firebase侦听器函数时不调用它?

例如:

this.gamestateURL.on('value', function(snapshot){
    self.GameStateChangeEvent(snapshot);
});

GameStateChangeEvent函数在设置侦听器后立即启动。

谢谢。

不幸的是,没有。文档特别声明:

此事件将使用存储在此位置的初始数据触发一次,然后在每次数据更改时再次触发。传递给回调的DataSnapshot将用于调用on()的位置。直到所有内容都同步后,它才会触发。如果该位置没有数据,则将使用空的DataSnapshot触发它(val()将返回null)。

然而,你可以这样做:

var ref = this.gamestateURL // or however you create a ref
function doSomethingWithAddedOrChangedSnapshot(snapshot) {
     // this function is called whenever a child is added
     // or changed
}
// assuming you have "timestamp" property on these objects
// it will not be called back with any snapshots on initialization
// because the timestamp of existing snapshots will not be greater
// than the current time
ref.orderByChild('timestamp')
   .startAt(new Date().getTime())
   .on('child_added', doSomethingWithAddedOrChangedSnapshot);
ref.on('child_changed', doSomethingWithAddedOrChangedSnapshot);
ref.once('value', function(snapshot){
    // get the initial state once
    // this snapshot represents all the items on this ref
    // this will only fire once on initialization
    initializeGameData(snapshot.val());
});

英文:

  • 创建一个处理更新/添加的子项的函数
  • 开始侦听在当前时间戳(自epoch以来的unix时间)之后添加的所有子级的child_added事件。这还假设您将时间戳存储在这些子项上
  • 开始侦听任何更改的子级的CCD_ 2事件
  • 获取ref的所有值一次以初始化数据
  • 不确定您的用例是否需要处理"child_removed"或"child_moved"