Javascript 有没有办法在Firebase中创建实时ForEach?
我一直在使用填充我的HTML表 到目前为止还不错,但是这个表不是实时的。我必须重新加载函数才能再次获取结果。如果我添加或删除一个条目,在我重新加载之前,视觉上不会发生任何变化 有没有一种方法可以让它变得实时? Firebase文档中的代码:Javascript 有没有办法在Firebase中创建实时ForEach?,javascript,foreach,firebase,firebase-realtime-database,Javascript,Foreach,Firebase,Firebase Realtime Database,我一直在使用填充我的HTML表 到目前为止还不错,但是这个表不是实时的。我必须重新加载函数才能再次获取结果。如果我添加或删除一个条目,在我重新加载之前,视觉上不会发生任何变化 有没有一种方法可以让它变得实时? Firebase文档中的代码: var query = firebase.database().ref("users").orderByKey(); query.once("value") .then(function(snapshot) { snapshot.forEach(functi
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的了解不够,我正在研究它。使用once()
你告诉数据库你只想获取当前值,不关心更新
获取实时更新的解决方案是使用on()
。由于每次更新都调用on()
处理程序时,承诺只能解析一次,因此应使用带有on()
的回调:
如果您关心更新UI以响应这些更新,那么您可能需要使用child\uu
处理程序。这些被称为JSON树中较低的一级,因此对于添加/更改/删除的每个用户来说。这允许您更直接地更新UI。例如,上面添加的子事件可以是:
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
})
这一点以及更多内容在我们的和中进行了相当广泛的介绍。使用once()
可以告诉数据库,您只想获取当前值,而不关心更新
获取实时更新的解决方案是使用on()
。由于每次更新都调用on()
处理程序时,承诺只能解析一次,因此应使用带有on()
的回调:
如果您关心更新UI以响应这些更新,那么您可能需要使用child\uu
处理程序。这些被称为JSON树中较低的一级,因此对于添加/更改/删除的每个用户来说。这允许您更直接地更新UI。例如,上面添加的子事件可以是:
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
})
这一点以及更多内容将在我们的和中详细介绍。非常感谢。再一次,请原谅我可怜的JS。非常感谢。再一次,请原谅我可怜的JS。