2

如何暂停服务器发送事件连接?甚至有可能,还是我必须关闭 SSE 然后重新打开它并再次分配所有事件处理程序?

例如我想做的(这都是理论上的,我不知道暂停/重启函数名称):

var source = new EventSource(url);

source.addEventListener("something", somefunction, false);
source.addEventListener("somethingElse", somefunction2, false);

//...some code

source.pause();


//...some code

source.restart();
4

1 回答 1

3

是的,这就是技术上需要发生的事情,但您可以将其抽象出来。注意:这个只有在你完成后才能连接.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();
于 2012-07-09T15:33:33.420 回答