Looking for javascript Answers? Try Ask4KnowledgeBase
Looking for javascript Keywords? Try Ask4Keywords

JavaScript Binding event listeners to EventSource


You can bind event listeners to the EventSource object to listen to different events channels using the .addEventListener method.

EventSource.addEventListener(name: String, callback: Function, [options])

name: The name related to the name of the channel the server is emitting events to.

callback: The callback function runs every time an event bound to the channel is emitted, the function provides the event as an argument.

options: Options that characterize the behavior of the event listener.

The following example shows a heartbeat event stream from the server, the server sends events on the heartbeat channel and this routine will always run when an event in accepted.

var eventSource = new EventSource("api/heartbeat");
eventSource.addEventListener("heartbeat", function(event) {
  var status = event.data;
  if (status=='OK') { 
    // do something