From eb8c713c987480e7a0362ae3de617ba0c0f27d7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Wed, 2 Sep 2015 02:57:38 -0300 Subject: .js.coffee -> .coffee It was initially required, but support for the shorthand has been supported since sprockets 2.1. Eventually 4.x will only support the shorthand version. Just want to get new people using the prefer stuff ASAP. --- lib/assets/javascripts/cable/connection.coffee | 65 ++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 lib/assets/javascripts/cable/connection.coffee (limited to 'lib/assets/javascripts/cable/connection.coffee') diff --git a/lib/assets/javascripts/cable/connection.coffee b/lib/assets/javascripts/cable/connection.coffee new file mode 100644 index 0000000000..2259ddcedd --- /dev/null +++ b/lib/assets/javascripts/cable/connection.coffee @@ -0,0 +1,65 @@ +# Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation. +class Cable.Connection + constructor: (@consumer) -> + @open() + + send: (data) -> + if @isOpen() + @webSocket.send(JSON.stringify(data)) + true + else + false + + open: -> + if @isOpen() + throw new Error("Must close existing connection before opening") + else + @webSocket = new WebSocket(@consumer.url) + @installEventHandlers() + + close: -> + @webSocket?.close() + + reopen: -> + @close() + @open() + + isOpen: -> + @isState("open") + + # Private + + isState: (states...) -> + @getState() in states + + getState: -> + return state.toLowerCase() for state, value of WebSocket when value is @webSocket?.readyState + null + + installEventHandlers: -> + for eventName of @events + handler = @events[eventName].bind(this) + @webSocket["on#{eventName}"] = handler + + events: + message: (event) -> + {identifier, message} = JSON.parse(event.data) + @consumer.subscriptions.notify(identifier, "received", message) + + open: -> + @disconnected = false + @consumer.subscriptions.reload() + + close: -> + @disconnect() + + error: -> + @disconnect() + + disconnect: -> + return if @disconnected + @disconnected = true + @consumer.subscriptions.notifyAll("disconnected") + + toJSON: -> + state: @getState() -- cgit v1.2.3