Skip to content

Instantly share code, notes, and snippets.

@jroxendal
Last active December 15, 2015 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jroxendal/5327191 to your computer and use it in GitHub Desktop.
Save jroxendal/5327191 to your computer and use it in GitHub Desktop.
A meditation on angular websocket services in coffescript.
myModule.factory 'websocket', ($q) ->
# to run, inject thus:
# myModule.run (websocket) ->
# websocket.connect("ws://localhost:8000")
# websocket.on "myCommand", (data) ->
# c.log "data received!", data
# websocket.send "my outgoing message"
def = $q.defer()
command_map = {}
ws = null
connect : (url) ->
ws = new WebSocket(url)
ws.onmessage = (evt) ->
data = JSON.parse evt.data
{command} = data
for listener in command_map[command]
listener(data)
ws.onopen = (evt) ->
def.resolve(evt)
ws.onerror = (evt) ->
def.reject(evt)
send: (msg) ->
def.promise.then () ->
ws.send(msg)
close : () ->
def.promise.then () ->
ws.close()
on : (command_str, callback) ->
unless command_str in command_map
command_map[command_str] = []
command_map[command_str].push callback
off : (command_str, callback) ->
command_map[command_str]?.splice command_map.indexOf(command_str), 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment