-
-
Save danr/5327335 to your computer and use it in GitHub Desktop.
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(callback), 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment