2017-04-15 7 views
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; 
} 
+1

"updateNotification"関数を呼び出すたびに、 "blur"と "focus"のための**新しい**イベントハンドラを作成しています。 –

答えて

0

あなたの全体の構造は間違っており、そのようには機能しません。 @ mpf82のコメントのように、メッセージを受け取るたびに新しいイベントハンドラを設定しないでください。

$(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; 
    }); 
}); 
関連する問題