Pregunta

How I pause a Server Sent Event connection? Is it even possible, or do I have to close the SSE and then reopen it and assign all of the event handlers again?

For example I would like to do (this is all theoretical, I do not know the pause/restart function names):

var source = new EventSource(url);

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

//...some code

source.pause();


//...some code

source.restart();
¿Fue útil?

Solución

Yes, that's what technically needs to happen but you can abstract it away. Note: This one only connects after you do .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();
        }
    }
}

Usage:

var source = new EventSource2(url);

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

source.connect();

source.disconnect();

source.connect();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top