From 3840fc30eca0f8b065815f2ce39e36a883d5a7ea Mon Sep 17 00:00:00 2001 From: Izabella Gal Date: Thu, 19 Sep 2013 15:28:01 +0300 Subject: [PATCH 1/2] Refactore the code to poll again into a separate method and add an error handler for the Ajax call, handler that calls this refactored method. --- jquery.eventsource.js | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/jquery.eventsource.js b/jquery.eventsource.js index 848d51f..85dfe83 100644 --- a/jquery.eventsource.js +++ b/jquery.eventsource.js @@ -181,20 +181,30 @@ lastEventId: stream.cache[ label ].lastEventId }); - setTimeout( - function() { - pluginFns._private.openPollingSource.call( this, options ); - }, - // Use server sent retry time if exists or default retry time if not - ( stream.cache[ label ] && stream.cache[ label ].retry ) || 500 - ); + pluginFns._private.pollAgain(options); } }, + error: function() { + pluginFns._private.pollAgain(options); + }, cache: false, timeout: 50000 }); } return source; + }, + pollAgain: function (options) { + var label = options.label; + if (stream.cache[ label ].timer) + clearInterval(stream.cache[ label ].timer); + + stream.cache[ label ].timer = setTimeout( + function() { + pluginFns._private.openPollingSource( options ); + }, + // Use server sent retry time if exists or default retry time if not + ( stream.cache[ label ] && stream.cache[ label ].retry ) || 500 + ); } } }, From ab4b0f84d716780cf5abe5dbb2f69070cbe9c174 Mon Sep 17 00:00:00 2001 From: Izabella Gal Date: Thu, 19 Sep 2013 15:29:10 +0300 Subject: [PATCH 2/2] In the fall-back implementation get the lastEventId value from the parsed data and add the Last-Event-ID header to the Ajax call. --- jquery.eventsource.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/jquery.eventsource.js b/jquery.eventsource.js index 85dfe83..8fdbd09 100644 --- a/jquery.eventsource.js +++ b/jquery.eventsource.js @@ -120,10 +120,15 @@ if ( stream.cache[ label ] ) { + var headers = {}; + if (stream.cache[ label ].lastEventId) + headers['Last-Event-ID'] = stream.cache[ label ].lastEventId; + source = jQuery.ajax({ type: "GET", url: options.url, data: options.data, + headers: headers, beforeSend: function() { if ( stream.cache[ label ] ) { this.label = label; @@ -174,8 +179,11 @@ this.label = label; - stream.cache[ label ].lastEventId++; - stream.cache[ label ].history[ stream.cache[ label ].lastEventId ] = parsedData; + if (parsedData[0]) { + stream.cache[ label ].lastEventId = parsedData[0].id; + stream.cache[ label ].history[ stream.cache[ label ].lastEventId ] = parsedData; + } + stream.cache[ label ].options.message.call(this, parsedData[0] ? parsedData[0] : null, { data: parsedData, lastEventId: stream.cache[ label ].lastEventId