     @_connectionPromise
 
   _leaveRoom: () ->
-    @ws.send JSON.stringify(type: 'leave')
-    @ws.close()
-    @ws = null
-    @_connectionPromise = null
+    [ws, @ws, @_connectionPromise] = [@ws, undefined, undefined]
+    ws.onclose = undefined
+    ws.send JSON.stringify(type: 'leave')
+    ws.close()
     @emit 'm2fa.room.left'
 
   _onOpen: (e) ->


  # Sent by mobile clients to request chrome application to repeat their 'request' message.
  _onRepeat: (data) ->
    @ws.send(@_lastRequest)

  # Sent by mobile clients to indicate the chrome application that one client is able to handle the 'request' message.
  _onAccept: (data) ->

    @_leaveRoom()

  _joinRoom: (pairingId) ->
    return @_connectionPromise if @_connectionPromise?
    d = Q.defer()
    @_connectionPromise = d.promise
    @ws = new WebSocket(@constructor.BASE_URL)
