javascript 如何关闭服务器发送的事件事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15839433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:17:28  来源:igfitidea点击:

How to close Server-Sent Events events

javascripthtmlserver-sent-events

提问by ahhmarr

I want to know how to close a server-sent events via JavaScript. Below is my dummy code:

我想知道如何通过 JavaScript 关闭服务器发送的事件。下面是我的虚拟代码:

var ser=new EventSource("path");
ser.onmessage=function(ev){
if(!ev)
   //want to close HERE!!
else
   console.log(ev);
}

回答by David Robinson Jr.

Here is the way that I found worked best for me

这是我发现最适合我的方式

var eventSource = new EventSource("path");
eventSource.onerror = eventSourceErrorFunction;
var eventSourceErrorFunction = function(event)
{
        if (event.eventPhase == EventSource.CLOSED) {
            that.eventSource.close();
            console.log("Event Source Closed");
        }  
} 

回答by Ian

The correct way to close a server side event is with the closemethod.

关闭服务器端事件的正确方法是使用close方法。

https://developer.mozilla.org/en-US/docs/Server-sent_events/EventSource#Method_overview

https://developer.mozilla.org/en-US/docs/Server-sent_events/EventSource#Method_overview

So you'd use:

所以你会使用:

var ser = new EventSource("path");
ser.onmessage = function (ev) {
    if (!ev)
       ser.close();
    else
       console.log(ev);
};

JavaScript is case sensitive, so you can't use .Close(), as it's a different thing than .close()and will be undefined in this case.

JavaScript 区分大小写,因此您不能使用.Close(),因为它.close()与这种情况不同,并且在这种情况下将是未定义的。