2015-01-02 35 views
1

我有一個Web應用程序,其中一些內部頁面使用EventSource從服務器接收實時更新。如何避免在內部鏈接中關閉EventSource時使用全局變量?

客戶端代碼如下所示:

var LiveClient = (function() { 
    return { 
     live: function(i) { 
      var source = new EventSource("/stream/tick"); 
      source.addEventListener('messages.keepalive', function(e) { 
       console.log("Client "+ i + ' received a message.'); 
      }); 
     } 
    }; 
})(); 

你可以看到在Heroku上現場演示:http://eventsourcetest.herokuapp.com/test/test/1。如果您打開開發者控制檯,則每次收到事件時都會看到一條消息。

問題是,當訪問內部鏈接時,EventSource保持打開狀態,即使訪問者從一個頁面移動到另一個頁面,也會打印消息 - 因此,如果您訪問頂部的三個鏈接,您將收到消息三個來源。

如何在用戶從一個內部頁面移動到另一個頁面後關閉以前的連接?

,我試圖哈克解決方法是使用全局變量的EventSource的對象,像這樣:

var LiveClient = (function() { 
    return { 
     live_global: function(i) { 
      // We set source as global, otherwise we were left 
      // with sources remaining open after visiting internal 
      // pages 
      if (typeof source != "undefined" && source != null) { 
       if (source.OPEN) { 
        source.close(); 
        console.log("Closed source"); 
       } 
      } 
      source = new EventSource("/stream/tick"); 
      source.addEventListener('messages.keepalive', function(e) { 
       console.log("Client "+ i + ' received a message.'); 
      }); 
     } 
    }; 
})(); 

演示在這裏:http://eventsourcetest.herokuapp.com/test/test_global/1,但我尋找能避免使用的解決方案全局變量如果可能。

所生成的HTML代碼是:

<a href="/test/test_global/1">Page 1</a> | 
    <a href="/test/test_global/2">Page 2</a> | 
    <a href="/test/test_global/3">Page 3</a> | 

<p>This is page 3</p> 
<script> 
    $(function() { 
    LiveClient.live_global(3); 
    }); 
</script> 

LiveClient.live_global(1);用於與全局變量的情況下。

回答

1

試試這個。我沒有測試過它。如果有效,你可以用this.source代替LiveClient.source這是一個更清潔的imo。

var LiveClient = (function() { 
    return { 
     source: null, 
     live_global: function(i) { 
      // We set source as global, otherwise we were left 
      // with sources remaining open after visiting internal 
      // pages 
      if (typeof LiveClient.source != "undefined" && LiveClient.source != null) { 
       if (source.OPEN) { 
        source.close(); 
        console.log("Closed source"); 
       } 
      } 
      LiveClient.source = new EventSource("/stream/tick"); 
      LiveClient.source.addEventListener('messages.keepalive', function(e) { 
       console.log("Client "+ i + ' received a message.'); 
      }); 
     } 
    }; 
})(); 
+0

是的,這樣做了,都是用'LiveClient.source'和'this.source'。萬分感謝 :) – user000001