diff options
author | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2015-09-02 02:57:38 -0300 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2015-09-02 02:57:38 -0300 |
commit | eb8c713c987480e7a0362ae3de617ba0c0f27d7f (patch) | |
tree | 7f5b9afd7a6326161c75270701f1e880e4f20263 /lib/assets/javascripts/cable/connection.coffee | |
parent | 0cf1db6be29fb2269d722bedd690641e0f949b36 (diff) | |
download | rails-eb8c713c987480e7a0362ae3de617ba0c0f27d7f.tar.gz rails-eb8c713c987480e7a0362ae3de617ba0c0f27d7f.tar.bz2 rails-eb8c713c987480e7a0362ae3de617ba0c0f27d7f.zip |
.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.
Diffstat (limited to 'lib/assets/javascripts/cable/connection.coffee')
-rw-r--r-- | lib/assets/javascripts/cable/connection.coffee | 65 |
1 files changed, 65 insertions, 0 deletions
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() |