 
   reopen: ->
     if @isOpen()
-      @webSocket.onclose = @open
-      @webSocket.onerror = @open
-      @webSocket.close()
+      @closeSilently => @open()
     else
       @open()
 
   isOpen: ->
     @isState("open")
+
+  # Private
 
   isState: (states...) ->
     @getState() in states

    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)

  onOpen: =>
    @consumer.subscribers.reload()

  onClose: =>
    @disconnect()

  onError: =>
    @disconnect()
    @webSocket.onclose = -> # no-op
    @webSocket.onerror = -> # no-op
    try @close()

  disconnect: ->
    @consumer.subscribers.notifyAll("disconnected")

    else
      false

  open: ->
    return if @isState("open", "connecting")
    @webSocket = new WebSocket(@consumer.url)
    @installEventHandlers()

  close: ->
    return if @isState("closed", "closing")
