2016-08-18 57 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。 –