2

I'm creating a class to handle event in socket.io, and I can't call this.io.emit in this class.

-- Socket file
class Socket {
    constructor(io) {
        this.io = io;
    }
    run() {
        this.io.on('connection', function(socket) {
            console.log('new client has connect', socket.id);
            this.io.emit('new-client', socket.id);
        });
    }
}
module.exports = Socket;



typeError: Cannot read property 'emit' of undefined
    at Namespace.<anonymous> (C:\Users\truon\OneDrive\Desktop\ProjectNodeJS\socket.js:8:12)
    at Namespace.emit (events.js:189:13)
    at Namespace.emit C:\Users\truon\OneDrive\Desktop\ProjectNodeJS\node_modules\socket.io\lib\namespace.js:181:14
    at process._tickCallback (internal/process/next_tick.js:61:11)
VoTruong
  • 43
  • 5

1 Answers1

1

inside the callback function, this is not equal to the Socket instance.

You need to use .bind or use arrow functions instead.

class Socket {
    constructor(io) {
        this.io = io;
    }
    run() {
        this.io.on('connection', socket => {
            console.log('new client has connect', socket.id);
            this.io.emit('new-client', socket.id);
        });
    }
}
module.exports = Socket;

Otherwise this is referencing the current Namespace object. If you don't want to use arrow functions, you can just do:

this.emit('new-client', socket.id)

run() {
    this.io.on('connection', function(socket) {
         console.log('new client has connect', socket.id);
         // this is referencing the Namespace
         this.emit('new-client', socket.id);
    });
}

You can read the following questions for more information regarding arrow functions & this.

Marcos Casagrande
  • 29,440
  • 5
  • 62
  • 77