Last active
December 15, 2015 21:39
-
-
Save jroxendal/5327191 to your computer and use it in GitHub Desktop.
A meditation on angular websocket services in coffescript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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