Reputation: 617
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
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