在下面的代码中,off()
在 on()
之前执行。发生这种情况是因为
The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized.
如文档中所述:https://firebase.google.com/docs/reference/js/firebase.database.Reference#on
quotesRef.orderByChild('index').on('value', function(snapshot) {
snapshot.forEach(function(childSnapShot) {
vm.allQuotes.push({
key: childSnapShot.key,
quoteTxt: childSnapShot.val().quote
})
})
})
quotesRef.off('value')
如何构造上述代码,以便仅在内容完全同步或实际调用 on
时调用 off()
。
谢谢
最佳答案
要在从数据库读取数据后调用 off
,请将其移至回调中:
quotesRef.orderByChild('index').on('value', function(snapshot) {
snapshot.forEach(function(childSnapShot) {
vm.allQuotes.push({
key: childSnapShot.key,
quoteTxt: childSnapShot.val().quote
})
})
quotesRef.off('value')
})
但正如 André 评论的那样,这与使用 once()
完全相同:
quotesRef.orderByChild('index').once('value', function(snapshot) {
snapshot.forEach(function(childSnapShot) {
vm.allQuotes.push({
key: childSnapShot.key,
quoteTxt: childSnapShot.val().quote
})
})
})
关于javascript - Firebase JS API : How to avoid `off()` getting executed before `on()` is called/finished executing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323284/