简体   繁体   English

每次收到新消息时更新标题中的值

[英]Updating value in title each time a new message is received

I'm trying to update value in the title when user clicks off my page/tab to notify about new messages and when he comes back to the tab to reset that value back to 0. For some reason the value is always incremented no matter what even though I'm setting it to 0 when user makes the tab active again, even though the rest of that function was executed properly changing document.title back to 'Chat'. 当用户单击我的页面/选项卡以通知新消息时,以及当他回到选项卡以将该值重置为0时,我正在尝试更新标题中的值。出于某种原因,无论如何,该值始终会增加即使当用户再次使选项卡处于活动状态时我将其设置为0,即使该功能的其余部分已正确执行,也将document.title更改回“ Chat”。

$(document).ready(function(){
  var unreadMessages = 0;
  var ws = new WebSocket("ws://localhost:8080/ws");
  ws.addEventListener("message", function(e){
    createMessage(e.data);
    unreadMessages = updateNotification(unreadMessages);

  });
});

function updateNotification(unreadMessages){
  unreadMessages++;
  $(window).blur(function(){
    if(unreadMessages>0){
      document.title = "("+ unreadMessages + ") Chat";
    }
  });
  $(window).focus(function(){
    unreadMessages=0;
    document.title = 'Chat';
  });
  return unreadMessages;
}

Your whole structure is wrong and can't work like that. 您的整个结构是错误的,不能那样工作。 Like @mpf82 commented don't set new eventhandlers everytime you receive a message. 就像@ mpf82一样,注释每次收到消息时都不要设置新的事件处理程序。 Try something like this: 尝试这样的事情:

$(document).ready(function(){
  var unreadMessages = 0;
  var blurred = false;
  var ws = new WebSocket("ws://localhost:8080/ws");
  ws.addEventListener("message", function(e){
    createMessage(e.data);
    if(blurred) document.title = "("+ ++unreadMessages + ") Chat";
  });
  $(window).blur(function(){
    blurred = true;
  });
  $(window).focus(function(){
    document.title = 'Chat';
    blurred = false;
    unreadMessages = 0;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM