【问题标题】:How to close previous EventSource如何关闭以前的 EventSource
【发布时间】:2019-06-08 13:02:23
【问题描述】:
<button onclick="hoge()">hoge</button>
<script>
function hoge(){
  if(es){
    es.close()
  }
  var es = new EventSource('/hoge')
  es.onmessage = function(e) {
    console.log(e)
  }
}
</script>

我想节省资源,所以点击并开始连接 EventSource。
每次点击都会开始新的连接,所以想断开之前的连接。
我尝试了上面的代码,但没有成功。请问我该怎么做。

【问题讨论】:

    标签: html ecmascript-6 server-sent-events


    【解决方案1】:

    当您第二次调用该函数时,您没有第一个 EventSource 的实际范围,因此变量 es 对您来说是空的,即使您已经实例化了 EventSource

    我不确定你为什么首先关闭并重新创建 EventSource,但这里有一个针对你的确切问题的解决方案:

    试试这个:

    <script>
    var eventSource;
    
    function hoge(){
        if(eventSource){
            eventSource.close()
        }
    
        eventSource = new EventSource('/hoge')
    
        eventSource.onmessage = function(e) {
            console.log(e)
        }
    }
    </script>
    

    请记住,eventSource 以这种方式位于全局范围内(或者换句话说,它直接附加到浏览器上下文中的窗口对象),因此您可能想要包装整个代码在一个模块中或至少在另一个功能中。简而言之,使用这个:

    <script>
    (function() {
        var eventSource;
    
        function hoge(){
            if(eventSource){
                eventSource.close()
            }
    
            eventSource = new EventSource('/hoge')
    
            eventSource.onmessage = function(e) {
                console.log(e)
            }
        }
    })();
    </script>
    

    【讨论】:

    • 谢谢。天气晴朗! var eventSource = { close : function(){ console.log(null) } } 这样,我不得不特意准备对象,并提前定义函数(关闭)。很麻烦,但是你无能为力
    • @nori 抱歉,没明白你的意思?你不需要准备任何东西。你为什么要做一个存根对象?除非有分配给变量的 eventSource 实例,否则不会调用“eventSource.close()”,因此您不必自己设置模拟“关闭”函数。当然,如果您不在另一个地方自己操作变量(显然您不应该这样做),这将起作用。
    • 哦!只声明变量!感谢您的公正建议解决了!
    • 我总是声明var eventSource = "" 等等。我不必替换值
    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多