2016-08-18 54 views
0

我一直在使用ForEach填充我的HTML表格。有沒有辦法在Firebase中實現ForEach?

到目前爲止好,但表是不是實時。我必須重新加載函數才能重新獲取結果。如果我添加或刪除一個條目,直到我重新加載纔會發生VISUALLY。

有沒有辦法讓這個實時?從火力地堡文檔 代碼:

var query = firebase.database().ref("users").orderByKey(); 
query.once("value") 
.then(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(); 
}); 
}); 

請原諒我對JS知識貧乏,我的工作就可以了。

回答

6

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

+0

非常感謝。再次請原諒我可憐的JS。 –