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

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


  reopen: ->
    if @isOpen()
      @closeSilently => @open()
    else
      @open()

  isOpen: ->
    @isState("open")

  # Private

  isState: (states...) ->
    @getState() in states
