Search code examples
javascriptajaxhtmlpushserver-sent-events

HTML5 → Dynamic associated Server Sent Events


I just started using SSE and wonder how I can make them more dynamic.

I'm using a Box to select users and an image and text changes corresponding to the username. Now I want to check for user updates via SSE and want the user to be still selectable.

I tried to add the eventSource when I'm changing the <select> box:

function setSelected(elm) {
    selectedName = elm.options[elm.selectedIndex].innerHTML;

    var eSource = new EventSource("getState.php?passVar=" + selectedName);
    eSource.onmessage = function(event) {
        document.getElementById("stateText").innerHTML = event.data;
    };
}

How can I reach my goal?

edit I have now added the eventSource successfully (I had an issue with the source itself).

But when I now add another source, I have actually two sources running. How can I remove the old one?


Solution

  • To remove the previous event source use the close() method. You're going to have to keep the reference to eSource around somehow to do this.