如何避免在网页返回时通过JS触发重复的PubNub通知

问题描述 投票:1回答:1

我在使用pubnub时遇到JS bootstrap notify事件的问题。

当BS通知事件被触发并且我切换到另一个页面然后返回到触发事件的页面 - 再次触发事件。喜欢它的缓存。比方说,JS事件在此页面上通过PubNub触发了4次(例如在聊天中),然后我切换到另一个页面。

然后我在浏览器中返回触发此事件的页面 - 我一次性收到4x通知!

我的问题:如何避免在页面返回时触发JS事件?

引导通知的JS代码:

$.notify({
    icon: "/profile/getprofileimage/{0}/100".format(userid),
    message: message
}, {
    icon_type: 'image',
    type: "success",
    delay: 400,
    allow_dismiss: false,
    animate: {
    enter: 'animated bounceInDown',
    exit: 'animated bounceOutUp'
}
});

PubNub:

channels['request-received-<?php echo $_SESSION["user"]["id"]; ?>'] = function (data) {
    notify(data.Message, data.From);
    play('newpending');

    if (typeof(hoodlister) !== "undefined" && hoodlister instanceof list)
        hoodlister.getItem(data.From).then(updateProfile);
    if (typeof(visitorlister) !== "undefined" && visitorlister instanceof list)
        visitorlister.getItem(data.From).then(updateProfile);
    if (typeof(pendingmatcheslister) !== "undefined" && pendingmatcheslister instanceof list)
        pendingmatcheslister.refresh();
};
javascript twitter-bootstrap pubnub
1个回答
1
投票

也许根据消息的timetoken保留警报缓存将解决您的问题。您可以在触发警报之前检查缓存。

当消息量较低时,PubNub timetokens(17位)几乎是唯一的,所以虽然这不是很优雅,但它可能是您需要的简单修复。

如果您触发了大量警报并且浏览器选项卡已经过了几天,那么缓存可能会变大,因此您可能需要处理它。

let cache = {};

pubnub.addListener({
    message: function(event) {
        if (!cache[event.timetoken]) {
            cache[event.timetoken] = true;
            // trigger the alert here
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.