Nicole Nguyeb
Nicole Nguyeb

Reputation: 37

Passing socket.io instance to JS object constructor

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?

Upvotes: 0

Views: 456

Answers (1)

Konrad
Konrad

Reputation: 24651

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
}

Upvotes: 1

Related Questions