通過使用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。 –