public
Last active

  • Download Gist
close.js
JavaScript
1 2 3 4 5 6 7 8
// close stream: label-a
$.eventsource('close', 'label-a');
 
// close stream: label-b
$.eventsource('close', 'label-b');
 
// close all open streams
$.eventsource('close');
server
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Server response MUST be Content-Type: text/event-stream
// Server response MUST be prepended with 'data: '
 
 
// Examples:
 
// PHP
header("Content-Type: text/event-stream\n\n");
echo 'data: this is a valid response';
 
 
// Python
print "Content-Type: text/event-stream"
print "data: this is a valid response"
streams.js
JavaScript
1 2 3 4 5 6 7 8
// Returns an object containing all the currently active eventsource streams
$.eventsource('streams')
 
 
var stream = $.eventsource('streams', 'label');
 
 
stream.history : Object containing the event message history for specified stream
usage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
$.eventsource({
// Assign a label to this event source
label: 'event-source-label',
 
// Set the file to receive data from the server
 
url: 'event-sources/server-event-source.php',
// Set the type of data you expect to be returned
// text, json supported
dataType: 'json',
// Set a callback to fire when the event source is opened
// `onopen`
open: function (data) {
// do something when the stream opens
},
 
// Set a callback to fire when a message is received
// `onmessage`
message: function (data) {
// Do something with the event source response
console.log(data);
}
});
 
 
// Close event sources by label name
 
$.eventsource('close', 'event-source-label');
varied.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// PLAIN TEXT EXAMPLE - NO CONTENT TYPE GIVEN
$.eventsource({
label: 'text-event-source',
url: 'test-event-sources/text-event-source.php',
open: function () {
// do something when the stream opens
},
message: function (data) {
// `data` will default to type/text
console.log(data);
}
});
 
// PLAIN TEXT EXAMPLE - HAS CONTENT TYPE
$.eventsource({
label: 'text-event-source-ct',
url: 'test-event-sources/text-event-source-ct.php',
dataType: 'text',
open: function () {
// do something when the stream opens
},
message: function (data) {
// `data` is explicitly type/text
console.log(data);
 
}
});
 
 
// JSON EXAMPLE - HAS CONTENT TYPE
$.eventsource({
label: 'json-event-source',
url: 'test-event-sources/json-event-source.php',
dataType: 'json',
open: function () {
// do something when the stream opens
},
message: function (data) {
// `data` is explicitly type/json
console.log(data);
}
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.