29

I'm trying to get data with server-sent event, what the different using

source.onmessage vs source.addEventListener?

evandrix
  • 6,041
  • 4
  • 27
  • 38
rezafahlevi08
  • 347
  • 1
  • 5
  • 10

2 Answers2

17

source.onmessage is the built in function wrapper for EventSource that is triggered when new data is sent to the client. It fires when no event attribute is returned (default) and doesn't fire when it is set.

addEventListener is similar, but differs in that it listens for a specific event name, and triggers on its presence, allowing you to separate your functionality for multiple events. You can then parse the JSON data returned. It can be used on any event type. Have a look at this example:

source.addEventListener("login", function(e) {
    // do your login specific logic
    var returnedData = JSON.parse(e);
    console.log(returnedData);
}, false);

This snippet will listen for a server message with event specified as login, then it triggers the callback function.

More info:

scrowler
  • 24,273
  • 9
  • 60
  • 92
  • 1
    if i'm using the messaging system for web workers, does it matter if I use addEventLisener or onmessage? you mention that addEventListener can be used to listen to multiple events, but isn't that the same thing if you decide to use onmessage vs onclick? you can listen to different events that way too – akantoword Jul 26 '16 at 21:20
  • 2
    Hi @akantoword - I'm not familiar with your application, but if you're sending different event names it's probably clearer and easier to use `addEventListener('myeventname')` to separate your logic. `onmessage` tends to be used more for simple messaging systems where different events are not used. Hope that helps. – scrowler Jul 26 '16 at 21:41
  • What `event` are you talking about? – pronebird Jun 21 '18 at 13:55
  • @highmaintenance "event" refers to the first argument in `addEventListener` in this case, not to be confused with the usual javascript `event` objects – scrowler Oct 04 '18 at 08:37
1

I assume you're talking about addEventListener('message') vs onmessage. They do the same thing, but I'd recommend using onmessage because with addEventListener, there's always a possibility of unexpectedly adding the same listener twice, e.g. due to a laggy page reload, or some hot-reload during development. In those cases the handler function could fire twice on every event, which leads to weird behaviors.

ZYinMD
  • 3,602
  • 1
  • 23
  • 32