core icon indicating copy to clipboard operation
core copied to clipboard

'this' in websocket joinRoom controller not set to class

Open adammcd9 opened this issue 9 years ago • 6 comments

When trying to join a room using websockets, 'this' in the joinRoom function does not seem to be bound to the class. In order to test this I installed a fresh version of adonis and changed the following files:

socket.js Append: Ws.channel('chat', 'ChatController')

Created ChatController in Ws/Controllers and add:

'use strict'

class ChatController {

  constructor (socket, request) {
    this.socket = socket
    this.request = request
  }

  * joinRoom (channel) {
    console.log('trying to join room', this.socket)
  }

  * onMessage (message) {
    console.log('message', this.socket)
  }

}

module.exports = ChatController

In a view I return:

<script src="https://unpkg.com/adonis-websocket-client/dist/ws.min.js"></script>
    <script>
      const io = ws('http://localhost:3333', {})
      const client = io.channel('chat')
      client.connect(function (error, connected) {
        if (error) {
          // do something
          console.log(error)
        }
        client.emit('message', 'Hello world')
        client.joinRoom('lobby', {}, function (error, joined) {
          // status
        })

      })    
    </script>

When I go to the page in my browser, I get the following message in the console output: trying to join room undefined

Is this expected behaviour? Docs here show that I should be able to access the socket.

The onMessage function is able to access this.socket as expected.

adammcd9 avatar Jul 22 '17 12:07 adammcd9

Try this:

* joinRoom (room, body, socket) {
    // socket
}
* leaveRoom (room, body, socket) {
    // socket
}

gcigd avatar Jul 22 '17 22:07 gcigd

Any news @Nublust ?

RomainLanz avatar Jul 28 '17 08:07 RomainLanz

Sorry for the delay @RomainLanz, only have the weekends to work on this :).

@K-Eo's suggestion did indeed work. Is it the docs that are wrong, or do you think there is a bug?

adammcd9 avatar Jul 29 '17 09:07 adammcd9

I have the exact same problem. Amazing framework btw

wimurk avatar Aug 30 '17 12:08 wimurk

Should be fixed in new version of websockets. Closing since this is wrong repo and websocket related issues are tracked separately on https://github.com/adonisjs/adonis-websocket repo

thetutlage avatar Oct 24 '17 06:10 thetutlage

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Mar 11 '20 12:03 lock[bot]