Module: Staticme::Scripts::Autoreload

Extended by:
Autoreload
Included in:
Autoreload
Defined in:
lib/staticme/scripts/autoreload.rb

Instance Method Summary collapse

Instance Method Details

#call(arg) ⇒ Object



87
88
89
# File 'lib/staticme/scripts/autoreload.rb', line 87

def call(arg)
  [200, {:'Content-Type' => 'application/javascript'}, [js_output]]
end

#js_outputObject



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/staticme/scripts/autoreload.rb', line 9

def js_output
    "(function() {\n  window.addEventListener('DOMContentLoaded', function() {\n\nvar WS_RECONNECT_TIMEOUT = 1000;\n\nvar Dispatcher = function(routes) {\n  this.init(routes);\n}\n\nDispatcher.prototype.init = function(routes) {\n  this.routes = routes;\n}\n\nDispatcher.prototype.dispatch = function(message) {\n  console.log('Dispatching data: ', message);\n  var event_name = message.event;\n  if (this.routes[event_name]) {\n    this.routes[event_name](message);\n  }\n}\n\nvar location   = window.location,\n    ws_url     = \"ws://\" + location.hostname + ':\#{Staticme.params[:ws_port].to_i}',\n    dispatcher = new Dispatcher({\n      'fs_change': function() {\n        console.log('Remote fs change, reloading the page...');\n        window.location.reload();\n      }\n    }),\n    ws = _open_ws(),\n    _reconnect_timer;\n\nfunction _open_ws() {\n\n  if (ws) {\n    _close_ws();\n  }\n\n  ws = new WebSocket(ws_url);\n\n  ws.onopen = function() {\n    window.clearTimeout(_reconnect_timer);\n    console.info('WebSocket connection has been established.');\n  }\n\n  ws.onmessage = function(event) {\n    var message = JSON.parse(event.data);\n    console.info('A new message received: ' . message);\n    dispatcher.dispatch(message);\n  }\n\n  ws.onerror = function(e) {\n    window.clearTimeout(_reconnect_timer);\n    console.error('An unexpected error occured.', e);\n    _reconnect_timer = window.setTimeout(_open_ws, WS_RECONNECT_TIMEOUT);\n  }\n\n  ws.onclose = function() {\n    window.clearTimeout(_reconnect_timer);\n    console.warn('WebSocket connection has been closed by the server.');\n    _reconnect_timer = window.setTimeout(_open_ws, WS_RECONNECT_TIMEOUT);\n  }\n\n  return ws;\n}\n\nfunction _close_ws() {\n  ws.close();\n  ws = null;\n}\n\n  }, false);\n})(window);\n"
end