2016-08-18 1 views
0

ForEachを使用してHTMLテーブルにデータを入力しています。FirebaseでリアルタイムForEachを作成する方法はありますか?

これまでのところとても良いですが、テーブルはリアルタイムではありません。結果を再度取得するために関数をリロードする必要があります。エントリを追加または削除すると、リロードするまでは何も表示されません。

これをリアルタイムで行う方法はありますか? Firebaseドキュメントから コード:

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()です。 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 
}) 

を。

+0

ありがとうございました。もう一度、私の貧しいJSを許してください。 –

関連する問題