Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io get socket inside a callback

I'm using socket.io for node.js. If you add an event handler like this:

io = require('socket.io')(http);
io.on('connect',function(socket){
    socket.on('some event',function(arg1,arg2){
       /// using socket to emit events for example
    }
}

Then I can access socket inside the callback for the 'some event' However what if I use it like this

io = require('socket.io')(http);
io.on('connect',function){
    socket.on('some event',myfunction);
}

function myFunction(arg1,arg2)
{
    //I want to use calling socket here.
}

How do I access socket in the later case? I need the socket to get the socket.id so I can know who called this event. Thanks

like image 811
Michael P Avatar asked Feb 10 '23 19:02

Michael P


1 Answers

Well, if I understand what you want to do, you can simply:

io = require('socket.io')(http);
io.on('connect',function){
    socket.on('some event',myfunction);
}

function myFunction(arg1,arg2)
{
    var socketId = this.id; //here you go, you can refer the socket with "this"
}

This is what I usually do to keep the code clean:

var on_potato = function(potatoData){

     var socket = this;
     var id = socket.id;

     //use potatoData and socket here
};

var on_tomato = function(tomatoData){

     var socket = this;
     var id = socket.id;

     //use tomatoData and socket here
};

var handleClientConnection = function (client) {

    client.on('potato', on_potato);
    client.on('tomato', on_tomato);
};

io.on('connection', handleClientConnection)
like image 75
Victor Avatar answered Feb 12 '23 10:02

Victor