-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.coffee
64 lines (54 loc) · 1.78 KB
/
client.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
((root, factory) ->
if typeof define is "function" and define.amd
define [], factory
else
root.Aasterinian = factory()
return
) this, () ->
connected: false
host: '$HOST'
port: '$PORT'
channel: '$CHANNEL'
socket: null
callbacks: {
default: (data)->
console.log "To use a custom callback define a function like : Aasterinian.Callback=function(data){...};, data is :"
console.log data
}
Activate: ->
do Aasterinian.LoadSocketIo unless typeof define is "function" and define.amd
do Aasterinian.TryToConnect
LoadSocketIo: ->
js = document.createElement("script")
js.type = "text/javascript"
js.src = "http://#{@host}:#{@port}/socket.io/socket.io.js"
document.head.appendChild js
Connect: ->
Aasterinian.socket=io.connect("http://#{@host}:#{@port}")
Aasterinian.socket.on "message", (data) ->
if Aasterinian.callbacks[data.channel]?
Aasterinian.callbacks[data.channel] JSON.parse(data.text)
else
Aasterinian.callbacks.default JSON.parse(data.text)
Aasterinian.Subscribe @channel, @Callback unless @channel=='undefined'
Aasterinian.connected = true
Subscribe: (channel, callback=null)->
Aasterinian.callbacks[channel]=callback if callback?
if Aasterinian.socket?.emit
Aasterinian.socket.emit "subscribe", channel: channel
else
setTimeout ->
Aasterinian.TryToConnect unless Aasterinian.socket?
console.log "retrying subscribe"
Aasterinian.Subscribe channel
,100
null
TryToConnect: ->
setTimeout ->
if io?
do Aasterinian.Connect
else
do Aasterinian.TryToConnect
, 100
if (Aasterinian?)
do Aasterinian.Activate