0

I'm trying to create a node.js server using socket.io. At the moment is just proof on concept. I created 2 files, first for server and anther for server side user.

server-core.js

'use strict';

var io = require('socket.io').listen(4567);
var user = require('./server-user');

var users = [];
io.sockets.on('connection', function(socket){
    var su = new user.ServerUser(socket);
    users[socket.id] = su;

    socket.on('auth', su.auth);

    socket.on('disconnect', su.disconnect);
});

io.sockets.on('disconnect', function(socket){
    console.log('disconnect');
   users[socket.id].disconnect();
});

console.log('Server started');

server-user.js

var ServerUser = (function(){

    function ServerUser(socket){
        this.socket = socket;
        console.log('serverUser-ctor ' + this.socket)
    }

    ServerUser.prototype.auth = function(data){
        console.log('auth received\r\n' + data);

        this.socket.emit('auth', {
            Id: data.Id,
            Timestamp: data.Timestamp,
            StringField: data.StringField
        });
    }

    ServerUser.prototype.disconnect = function(){
        console.log('Client disconnected');
    }

    return ServerUser;
})();


module.exports = {
    ServerUser: ServerUser
};

my C# client connects fine to server, but when user-server tries to send the answer back the this.socket is undefined in ServerUser.prototype.auth method. This tell me that the instance of the ServerUser that I create in server-core is not being hold and when 'auth' method is called a new instance of object is actually being created.

To proof this I replaced this line

socket.on('auth', su.auth);

with such one

socket.on('auth', function(data){su.auth(data);});

After this it worked as needed. Is this the correct way to write JS code? Is there a better way to separate logic under separate files and classes when writing large node.js applications?

Thx for any opinions.

0

1 Answer 1

2

The problem is the invocation context. When you pass su.auth to socket.on(), this no longer refers to su inside of auth. So, there are a couple of ways to fix that. Using an anonymous function, as you found, is one. Function.bind is another:

socket.on('auth', su.auth.bind(su));
Sign up to request clarification or add additional context in comments.

1 Comment

Of the two, the bind is probably the better choice. Performance is probably indistinguishable, but the second more clearly indicates what problem is being solved, and assists in debugging since anonymous functions can be hard to trace.

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.