来自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)
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)
小智 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(),因此无需捕获空数据。