javascript - 为什么 Firebase 事件 'child_added' 在 'value' 事件之后触发?

标签 javascript firebase

根据 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 支持人员提供的出色反馈:

  1. 这里使用 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.

    Frank's correction to that example 显示了这一点。

  2. 修改后的示例再次打破了“保证”,因为(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/

相关文章:

firebase - 带有 Firebase Auth 的 Flutter Web 无法在本地工作,但在部署在云中时可以工作

javascript - Superfish IE7 z-index 错误与 Nivo slider 或 wordpress 中的 Photospace

javascript - 为什么我不能在元素上调用 Polymer 函数?

javascript - 覆盖 jPlayer 中的负剩余时间

javascript - 使用 Jasmine 测试 Angular Controller 中的非作用域函数

javascript - 将 Excel 上传到 Google Cloud Storage 时出错

javascript - React Native 中的 FlatList 不会从 firebase 渲染子项

android - Firebase UI + Android 加载动画

Firebase:多个应用程序连接到单个 Firestore

javascript - 如何使用 angular 2 或 javascript 从客户端机器获取日期和时间格式?