Search code examples
javascriptjqueryserver-sent-events

javascript - reference DOM for a variable every time


The title of the question may seem misleading as I know you should not use variable if you want to reference the DOM every time. However, the scenario is a bit different; I've created an SSE script that works perfectly the first time the page is loaded but since the content of the page is constantly changing it won't always work.

var objts = $(".newsItem:first").data("ts");
var objid = $(".newsItem").data("id"); 
var ids = $.makeArray(objid); //variable of IDS
var ts = $.makeArray(objts); //variable of ts

var source=new EventSource("AJAX/get_feed_updates.php?ids=" + ids + "&ts="+ ts +"");

source.onmessage=function(event)
  {
    if (event.data > 0){
        document.title = '(' + event.data + ') ' + originalTitle;

    if (event.data == 1){// no plurals
           $("#refreshFeed").fadeIn('slow').html(event.data + ' more news item.');
     }

     if (event.data > 1){ //plurals
        $("#refreshFeed").fadeIn('slow').html(event.data + ' more news items.');
     }
}
};

As you can see the first variable get the data into an array to put into the EventSource url. Obviously, this will not continue updating as the page does and neither wil source. I tried stringing everything together so instead of source.onmessage... it became;

new EventSource("..." + $.makeArray($".newsItem")...).onmessage=function(event)

But that did not work as the Event Source does not change. I want the DOM to be referenced EVERY single time the SSE source is requested. I know this is not a good way of doing these things but I can't see a way around it in this case.


Solution

  • For this case I would not use EventSource since you need to pass it information.

    Try using websockets or use some sort of Comet technique.