once()
を使用すると、データベースに現在の値を取得したいだけで、更新については気にしないと言っています。
リアルタイム更新を取得するソリューションは、on()
です。 on()
ハンドラがすべての更新のために呼ばれながら、約束は一度しか解決できますので、あなたはon()
でコールバックを使用する必要があります。
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);
});
を使用すると、アップデートに対応してUIを更新する気にならば、あなたはおそらくしたいですよchild_
ハンドラを使用してください。これらは、JSONツリーのレベルを1つ下にして呼び出されます。したがって、追加/変更/削除される各ユーザについて、あなたの場合はそうです。これにより、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);
});
今、あなたと他のイベント処理できます。これは、より多くのが私たちのguide for web developersにし、reference documentationにかなり広範囲にカバーされ
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を許してください。 –