What is the difference between onmessage and addEventListener?

I am trying to get data with an event sent by the server, which is different using

source.onmessage vs source.addEventListener ?

+8
javascript server-sent-events
source share
1 answer

source.onmessage is a built-in wrapper function for EventSource , which is launched when new data is sent to the client. It fires when the no event attribute is returned (the default) and not when it is set.

addEventListener similar, but differs in that it listens for a specific event name and fires its presence, which allows you to split your functions into several events. Then you can parse the returned JSON data. It can be used for any type of event. Take 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 listens for the server message with the event specified as login , then it calls the callback function.

Additional Information:

+5
source share

All Articles