Skip to content

Instantly share code, notes, and snippets.

@danr
Forked from jroxendal/gist:5327191
Created April 6, 2013 19:34
Show Gist options
  • Save danr/5327335 to your computer and use it in GitHub Desktop.
Save danr/5327335 to your computer and use it in GitHub Desktop.
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(callback), 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment