我如何暂停服务器发送事件连接?它是否可能,或者我是否必须关闭SSE然后重新打开它并再次分配所有事件处理程序?
例如我想做(这是理论上的,我不知道暂停/重启函数名称):
var source = new EventSource(url);
source.addEventListener("something", somefunction, false);
source.addEventListener("somethingElse", somefunction2, false);
//...some code
source.pause();
//...some code
source.restart();
答案 0 :(得分:2)
是的,这是技术上需要发生的事情,但你可以把它抽象出来。注意:此项仅在您执行.connect()
function EventSource2(url) {
this.url = url;
this.es = null;
this.listeners = {};
}
EventSource2.prototype = {
constructor: EventSource2,
connect: function() {
this.es = new EventSource(this.url);
this.bindEvents();
},
disconnect: function() {
this.es.close();
this.es = null;
},
bindEvents: function() {
for ( var type in this.listeners ) {
var evs = this.listeners[type];
for( var i = 0; i < evs.length; ++i ) {
this.es.addEventlistener( type, evs[i], false );
}
}
},
addEventListener: function( type, fn ) {
if( !this.listeners[type] ) {
this.listeners[type] = [];
}
this.listeners[type].push( fn );
if( this.es ) {
this.bindEvents();
}
}
}
用法:
var source = new EventSource2(url);
source.addEventListener("something", somefunction, false);
source.addEventListener("somethingElse", somefunction2, false);
source.connect();
source.disconnect();
source.connect();