Child_changed 在页面加载时下载所有内容

Child_changed downloads everything on page load

var notifRef = new Firebase(webSocketBaseURL + "/notifications/custom:" + userId);

var $results = $("#notifications_nav"); //div in nav for notifcations

notifRef.limitToLast(5).once("value", function(snapshot) {
    var lastKey = null; // at least 1 key is always present
    var count = 0; // because startAt is inclusive, we have to ignore first child_added
    snapshot.forEach(function(data) {
        addNotifications(data.val());
        lastKey = data.key();
    });
    checkNotifications();
    notifRef.orderByKey().startAt(lastKey).on('child_added', function(snap) {
        if (count > 0) {
            addNotifications(snap.val());
            checkNotifications();
        }
        count++;
    });
});

notifRef.on('child_changed', function(snapshot) {
    var notification = snapshot.val();
    var existingNotif = $results.find('.top-cart-item').eq(0);
    if (notification.type == existingNotif.data("type") && notification.link == existingNotif.find("a").attr('href') && notification.message == existingNotif.find("a").text()) {
        existingNotif.find(".top-cart-item-price.time").livestamp(moment(parseInt(notification.timestamp)).unix());
        existingNotif.find(".top-cart-item-quantity").text("x " + notification.count);
        checkNotifications(); // append +1 to new notifications
    }
});

你好,基本上就是这个问题

当我有 child_changed 事件时,在页面加载时加载来自 firebase URL 的所有数据。为什么 child_changed 在页面加载时加载?是不是有些数据改变了就只听,然后只拍通知?

我检查了 inspect element 中网络选项卡下的框架,确实,当 notifRef.on('child_changed') 被注释掉时,最后只下载了 5 个通知,就像在 notifRef.limitToLast(5).once("value".

中一样

如果您想了解更多细节或我在这里遗漏了什么显而易见的事情,请告诉我?

编辑:

代码中发生的事情就像 facebook 右上角通知区域的 5 个最新通知。

notifRef.limitToLast(5).once("value" 这是拉取 5 个最新通知。我正在那里做一个循环来获取最后一个密钥。现在下一部分是我如何实现您最常见的问题:如何获取页面加载后添加的 children?

因为在 limitToLast(5) 的前一部分中,我添加了最新的密钥,notifRef.orderByKey().startAt(lastKey).on('child_added' 我只听新添加的 children,因为它按密钥排序并从最后一个。

现在是棘手的部分,因为一种通知类型是 new message from user 并且如果用户发送多次,那么不是每次都添加新的 child,最后一个键只有一个新的递增 属性 count 这意味着从用户那里收到了多少条新消息。但这仅适用于最后一个通知是来自该用户的消息的情况。如果上一条通知不是来自该用户的消息,而下一条通知是来自该用户的新消息,那么它只会添加新的 child.

让我们 slice-and-dice 稍微检查一下您的代码,看看发生了什么:

var notifRef = new Firebase(webSocketBaseURL + "/notifications/custom:" + userId);

notifRef.on('child_changed', function(snapshot) {...

请注意,您在这里没有以任何方式订购或限制 notifRef。因此,您正在该位置的所有 children 上监听 child_changed 事件。

但是你混合 valuechild_ 事件的方式以及不同的查询对我来说很难解析,所以我可能误解了你的 use-case.