0

I read this question and attempted to do the solution, however I am trying to pass my instance of io to an object constructor instead of a class. I originally attempted to do something like...

//index.js
const {CONNECTION, CREATE_ROOM} = require('./SignalTypes')

const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const Lobbies = require('./lobby')

let lobbies = new Lobbies(io)

io.of('/menu').on(CONNECTION, (socket) => {
    console.log(`User connected to main menu`)

    socket.on(CREATE_ROOM, () => {
        const roomKey = lobbies.createLobby()
        socket.emit(ROOM_CREATED, roomKey)
    })
    ...
})

And my Lobbies file looks like...

//lobby.js
const shortid = require('shortid')

function Lobbies(io) {
    this.io = io;
    this.lobbies = {}
}

Lobbies.prototype.createLobby = () => {
    let roomKey = shortid.generate()

    //create namespace for new lobby
    const lobbyNamespace = this.io.of(`/${roomKey}`)  // issue
    
    this.lobbies[roomKey] = new Lobby(roomKey, lobbyNamespace)
    return roomKey
}
//Lobby object constructor defined later
...
module.exports = Lobbies

However I keep running into errors in which it says io is undefined at the line

//lobby.js
const lobbyNamespace = this.io.of(`/${roomKey}`)
//TypeError: Cannot read property 'of' of undefined

I was wondering if there's a way to pass my io object to my object constructor without having to change it into an ES6 class or something. Any suggestions?

1 Answer 1

1

You are losing this reference when using arrow function syntax. I don't know why do you want to use old, hard-to-read syntax, but if you want that instead of class you should do:

Lobbies.prototype.createLobby = function() {
    let roomKey = shortid.generate()

    //create namespace for new lobby
    const lobbyNamespace = this.io.of(`/${roomKey}`)  // issue
    
    this.lobbies[roomKey] = new Lobby(roomKey, lobbyNamespace)
    return roomKey
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.