通过使用once()
您告诉该数据库,您只想获取当前值并且不关心更新。
获得实时更新的解决方案是使用on()
。如果你关心响应这样的更新更新UI
var query = firebase.database().ref("users").orderByKey();
query.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
}, function(error) {
console.error(error);
});
,你可能会想:既然当了on()
处理程序被调用每次更新一个承诺只能解决一次,你应该使用一个回调函数on()
使用child_
处理程序。这些在你的JSON树中被调用了一个较低的级别,所以在你的情况下,每个用户被添加/更改/删除。这使您可以更直接地更新UI。例如,child_added
事件上面可能是:
var query = firebase.database().ref("users").orderByKey();
query.on("child_added", function(snapshot) {
var key = snapshot.key;
var data = snapshot.val();
// TODO: add an element to the UI with the value and id=key
});
}, function(error) {
console.error(error);
});
现在,您可以处理其他事件有:
query.on("child_changed", function(snapshot) {
// TODO: update the element with id=key in the update to match snapshot.val();
})
query.on("child_removed", function(snapshot) {
// TODO: remove the element with id=key from the UI
})
这一点,更是覆盖在我们的guide for web developers相当广泛,在reference documentation 。
非常感谢。再次请原谅我可怜的JS。 –