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

时间:2015-08-26 01:38:32

标签: javascript firebase

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元素中网络标签下的框架,实际上,当notifRef.on('child_changed')被注释掉时,只会下载最后5个通知,因为它位于notifRef.limitToLast(5).once("value"中。

如果您想了解更多细节,或者我在这里错过了哪些显而易见的事情,请告诉我们?

编辑:

代码中发生了什么,就像5个最新通知的Facebook右上角通知区域一样。

notifRef.limitToLast(5).once("value"这会提取5条最新通知。我正在做一个循环来获取最后一个键。接下来的部分是我如何实现你最常见的问题:如何让页面加载后添加的孩子?

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

现在是棘手的部分,因为一个通知类型是new message from user并且如果用户多次发送,那么最后一个密钥只有一个新的递增属性count,而不是每次都添加新的子项。表示从用户收到多少新消息。但这只是在最后一次通知是来自该用户的消息的情况下。如果上次通知不是来自该用户的消息,而下一个通知是来自用户的新消息,那么它只会添加新的子消息。

1 个答案:

答案 0 :(得分:0)

让我们对您的代码进行切片和切块,看看发生了什么:

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

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

请注意,您并未在此处以任何方式订购或限制notifRef。所以你正在听那个地方所有孩子的child_changed个事件。

但是你混合valuechild_事件的方式和不同的查询对我来说很难解析,所以我可能误解了你的用例。