WebSocket best practice

javascript, websocket

Solution

Since there is a single 'onmessage' event fired, it would seem cleanest to have a single handler for this. Otherwise things can get messy very quickly, since there is no central place where it's apparent what happens once the event fires.

Additionally, with a multitude of handlers, that's potentially a lot of code which all gets called on each message. This may be uncritical for a lot of use cases, but with high message frequencies and/or time-critical handling, having a single function seems the more efficient solution.

Incidentially, a single handler function is what Mozilla has in its WebSocket tutorial

Problem

I'm playing with Websockets and I have ended with a quite few socket.on(msg, function()) events. So I'm wondering what is the best practice, just keep adding socket.on events for each case or use just one event with sub-events that will be handled in a ``` switch(json.type) { case 'maps' : add_maps_from_json(json); break; case 'fList': show_floor_list(json); break; ... case 'xxx': ```

Original source