 
     error: ->
       @consumer.subscriptions.notifyAll("disconnected")
-      @closeSilently()
 
   toJSON: ->
     state: @getState()

    return state.toLowerCase() for state, value of WebSocket when value is @webSocket?.readyState
    null

  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)

  events:
    message: (event) ->

      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")
