Rana Deep
Rana Deep

Reputation: 617

Accessing socket.io scope from outer scope

I have a scenario where user sends a POST request, in express I set up a route, get the post data, validate it, store it in db then I need to broadcast it to all sockets connected. But since the socket variable is available inside io.sockets.on('connection') I might be able to access the inner scope of it with a closure this way:

Var a = {}; //global
io.sockets.on('connection',function(socket){
    a.inner = function(data){
        socket.broadcast.emit('boo',data)
    }
}

Then call a.inner(data)

Is this normal? is there a better way to access or call inner functions ?

Thanks

Upvotes: 1

Views: 918

Answers (1)

luin
luin

Reputation: 1995

I always use this:

var userIdSocketMapper = {};
io.sockets.on('connection', function (socket) {
  var userId = socket.handshake.userId;
  userIdSocketMapper[userId] = socket;
});

app.post('/:userId', function(req, res) {
   var socket = userIdSocketMapper[req.params.userId];
   if (socket) {
     socket.broadcast.emit('boo', data);
   }
});

Upvotes: 2

Related Questions