diff options
Diffstat (limited to 'lib')
-rw-r--r-- | lib/assets/javascripts/cable/connection.js.coffee | 58 |
1 files changed, 36 insertions, 22 deletions
diff --git a/lib/assets/javascripts/cable/connection.js.coffee b/lib/assets/javascripts/cable/connection.js.coffee index bb3bc5dd12..4d2c1018aa 100644 --- a/lib/assets/javascripts/cable/connection.js.coffee +++ b/lib/assets/javascripts/cable/connection.js.coffee @@ -9,13 +9,10 @@ class Cable.Connection else false - open: => + open: -> return if @isState("open", "connecting") @webSocket = new WebSocket(@consumer.url) - @webSocket.onmessage = @onMessage - @webSocket.onopen = @onOpen - @webSocket.onclose = @onClose - @webSocket.onerror = @onError + @installEventHandlers() close: -> return if @isState("closed", "closing") @@ -23,15 +20,15 @@ class Cable.Connection reopen: -> if @isOpen() - @webSocket.onclose = @open - @webSocket.onerror = @open - @webSocket.close() + @closeSilently => @open() else @open() isOpen: -> @isState("open") + # Private + isState: (states...) -> @getState() in states @@ -39,21 +36,38 @@ class Cable.Connection return state.toLowerCase() for state, value of WebSocket when value is @webSocket?.readyState null - onMessage: (message) => - data = JSON.parse message.data - @consumer.subscribers.notify(data.identifier, "received", data.message) + closeSilently: (callback = ->) -> + @uninstallEventHandlers() + @installEventHandler("close", callback) + @installEventHandler("error", callback) + try + @webSocket.close() + finally + @uninstallEventHandlers() + + installEventHandlers: -> + for eventName of @events + @installEventHandler(eventName) + + installEventHandler: (eventName, handler) -> + handler ?= @events[eventName].bind(this) + @webSocket.addEventListener(eventName, handler) + + uninstallEventHandlers: -> + for eventName of @events + @webSocket.removeEventListener(eventName) - onOpen: => - @consumer.subscribers.reload() + events: + message: (event) -> + {identifier, message} = JSON.parse(event.data) + @consumer.subscribers.notify(identifier, "received", message) - onClose: => - @disconnect() + open: -> + @consumer.subscribers.reload() - onError: => - @disconnect() - @webSocket.onclose = -> # no-op - @webSocket.onerror = -> # no-op - try @close() + close: -> + @consumer.subscribers.notifyAll("disconnected") - disconnect: -> - @consumer.subscribers.notifyAll("disconnected") + error: -> + @consumer.subscribers.notifyAll("disconnected") + @closeSilently() |