根据 Firebase documentation :
Value events are always triggered last and are guaranteed to contain updates from any other events which occurred before that snapshot was taken.
这是一个简单的示例 ( jsbin ),其中 child_added
在之前 value
触发。使用当前最新的 Firebase 版本 (2.3.1) 确认了此行为:
var ref = new Firebase("https://reform.firebaseio.com");
ref.child('pets').once('value', function(snapshot) {
snapshot.forEach(function(pet) {
console.log("Pet: " + pet.key());
pet.ref().child('food').once('value', function (foods) {
console.log('value event called for ' + pet.key());
});
pet.ref().child('food').once('child_added', function (foods) {
console.log('child_added event called for ' + pet.key());
});
});
});
在此示例中,控制台日志将为:
Pet: cat
Pet: dog
value event called for cat
child_added event called for cat
value event called for dog
child_added event called for dog
为什么在这种情况下 child_added
事件最后触发?这是否违反了文档的保证?
最佳答案
总结评论中和 Firebase 支持人员提供的出色反馈:
这里使用
on()
而不是once()
来注册事件监听器是最有意义的。在 example of the original post 中,并引用 Firebase 支持:The on() callback is registered, and when the once() callback is registered it is ordered in reference to the on() callback. Once the once() callback is fired, it's automatically deregistered. Even though the execution of the events are done in a certain order (due to javascript being single threaded), they are being calculated separately from each other.
修改后的示例再次打破了“保证”,因为(Firebase 支持):
The data is already locally on the client. So once you have run ref.child('pets').on() and the callback happens, all the data under /pets has been retrieved to the client. Now in the callback processing, you are adding additional callbacks to the existing data. When the callback is being added, the client library is immediately firing the callback without waiting for the second one to be registered since all the data is available.
由于我想在数据是本地的情况下强制执行保证,因此我只需在
value
监听器之前注册child_added
监听器,如 correction to the modified example 中所示.
关于javascript - 为什么 Firebase 事件 'child_added' 在 'value' 事件之后触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516346/