add to WebSocket.onmessage() like how jQuery adds to events?

append, function, javascript, jquery, websocket

Solution

You can create a wrapper which will handle WS events on itself. See this example CoffeeScript:

class WebSocketConnection
  constructor: (@url) ->
    @ws           = new WebSocket(@url)
    @ws.onmessage = @onMessage
    @callbacks    = []

  addCallback: (callback) ->
    @callbacks.push callback

  onMessage: (event) =>
    for callback in @callbacks
      callback.call @, event

# and now use it
conn = new WebSocketConnection(url)
conn.addCallback (event) =>
  console.log event

Problem

I'm writing a single page ws++ site, and I'd like to keep my code grouped first by "page" (I think I need a new word since it never posts back) then by section then by concept etc. I'd like to split up `WebSocket.onmessage` across my code much in the same way that `$('#someElement')` can constantly have an event like `click(function(){})` added to it. Can this be done with `WebSocket.onmessage(function(){})`? If so, how? As some jQuery programmers happily know, an event can be initially set then added to in multiple places across the js. That's my favorite thing about js, the "put it anywhere as long as it's in order" ability. This makes code organization so much easier for me at least. With WebSockets, really, the action client side for me so far is with the `WebSocket.onmessage()` handler since `WebSocket.send()` can be used anywhere and really just ports js data to the server. `onmessage()` now owns my page, as whatever's in it initiates most major actions such as fading out the login screen to the first content screen upon a "login successful" type message. According to my limited understanding of js, the `onmessage()` handler must be set all in one place. It's a pain to keep scrolling back/tabbing to another file to make a change to it after I've changed the js around it, far, far, away. How can I add to the `WebSocket.onmessage()` handler in multiple places across the js?

Original source

Related problems