Reputation: 39
On my server side, I can't get a listener attached to a client connection to respond. I can successfully emit a message when a client connects, as well as successfully respond to the server from the client side, but can't respond beyond that.
// communication scheme
//
// (1) server responds to client connection with 'welcome'
// (2) client immediately responds with 'thanks'
// (3) server's User class SHOULD respond with 'np', however this
// is never emitted
class User {
constructor(socket) {
this.socket = socket;
this.socket.on('thanks', function() {
// !!! Point at which code doesn't work
// the code inside here is never reached
this.socket.emit('np');
})
this.socket.emit('welcome');
}
}
class Server {
constructor(port) {
this.app = require('express')();
this.server = require('http').Server(this.app);
this.io = require('socket.io')(this.server);
this.server.listen(port);
this.io.on('connection', function(socket) {
var user = new User(socket);
});
}
}
this.io.on('welcome', function() {
this.io.emit('thanks', {});
});
this.io.on('np', function() {
console.log("I never get here either");
});
Upvotes: 1
Views: 318
Reputation: 11
You were trying to access User.socket but were actually accessing the User.socket.socket when trying to emit 'np'
from the server. I changed it to use an ES6 arrow function to fix the issue, if you want to read up on it some arrow function this should explain it pretty well.
class User {
constructor(socket) {
this.socket = socket;
this.socket.on('thanks', () => {
this.socket.emit('np');
});
this.socket.emit('welcome');
}
}
Upvotes: 1
Reputation: 2330
I think it has to do the value of this
which changes in the body of the callback from the 'thanks' event. this
no longer refers to the User object, it refers to the object which called the function which is user.socket
. You are basically calling user.socket.socket.emit
which doesn't exist. There is a trick around this, store the scope of this in another variable so we can access it later.
class User {
constructor(socket) {
this.socket = socket;
var that = this;
this.socket.on('thanks', function() {
// !!! Point at which code doesn't work
// the code inside here is never reached
that.socket.emit('np');
})
this.socket.emit('welcome');
}
}
Upvotes: 1