Firebase child_added只会添加子项

Mat*_*son 52 firebase

来自Firebase API:

已添加子项:此事件将针对此位置的每个初始子项触发一次,并且每次添加新子项时都会再次触发该事件.

一些代码:

listRef.on('child_added', function(childSnapshot, prevChildName) {
    // do something with the child
});
Run Code Online (Sandbox Code Playgroud)

但是因为在这个位置每个孩子调用了一次函数,有没有办法只获得实际添加的孩子?

Kat*_*ato 39

要跟踪自某个检查点以来添加的内容而不获取以前的记录,您可以使用endAt()limit()获取最后一条记录:

// retrieve the last record from `ref`
ref.endAt().limitToLast(1).on('child_added', function(snapshot) {

   // all records after the last continue to invoke this function
   console.log(snapshot.name(), snapshot.val());

});
Run Code Online (Sandbox Code Playgroud)

  • 加藤对GitHub有一个很好的解释,[这里](https://gist.github.com/katowulf/6383103). (3认同)
  • 您的意思不清楚。这仅适用于有序集,但是如果您需要订购其他商品(除有序集之外?)...此外,您的评论并不能帮助任何人了解如何在Firebase中获取添加子事件。 (2认同)

tib*_*eoh 36

limit()方法已弃用.limitToLast()limitToFirst()方法取代它.

// retrieve the last record from `ref`
ref.limitToLast(1).on('child_added', function(snapshot) {

   // all records after the last continue to invoke this function
   console.log(snapshot.name(), snapshot.val());
   // get the last inserted key
   console.log(snapshot.key());

});
Run Code Online (Sandbox Code Playgroud)

  • 我尝试过这种方法,但要注意一件事:如果最后一条记录被删除,例如用户发布评论并立即将其删除(例如,这是一个错误)上面的.on()函数将再次被召唤.我解决了添加一个时间戳并检查添加的孩子是否小于一秒钟,如果它更旧,它是一个旧记录并且没有添加.为此,请看一下ref.child('.info') (5认同)
  • 我不明白 - 这不会只是得到最后一项吗?那么"只有在绑定到此事件后添加的项目"呢? (4认同)

小智 6

由于调用ref.push()没有数据的方法根据时间生成路径键,这就是我所做的:

// Get your base reference
const messagesRef = firebase.database().ref().child("messages");

// Get a firebase generated key, based on current time
const startKey = messagesRef.push().key;

// 'startAt' this key, equivalent to 'start from the present second'
messagesRef.orderByKey().startAt(startKey)
.on("child_added", 
    (snapshot)=>{ /*Do something with future children*/}
);
Run Code Online (Sandbox Code Playgroud)

请注意,实际上没有将任何内容写入返回的引用(或“键”)ref.push(),因此无需捕获空数据。