I have a question to which I am trying to figure out the answer
For example, I structured the sockets like this
const io = require('socket.io')(server, {
cors: {
origin: "*"
}
});
// sockets events
const onConnection = require('./sockets/events/connection');
io.on("connection", onConnection);
const search = require('./s');earch
const onConnection = async (socket) => {
console.log(`Client connected ${socket.id}`);
socket.on('search', search);
socket.on('disconnect', (reason) => {
console.log(`Client disconnected with reason: ${reason}`)
})
};
module.exports = onConnection;
But in that search function, I would also like to pass the "socket" argument so that I can still have access to the socket functions
const onSearch = async (socket) => {
console.log(socket);
console.log(500);
}
module.exports = onSearch;
So my question is when I access that event (search) in socket.on, how could I send the socket further?
I tried to pass as a function
socket.on('search', metasearch(socket);
But it didn't work..
CodePudding user response:
I'm not familiar with socket.io
but you should be able to refactor the callback like this:
const onSearch = (socket) => async (data) => {
console.log(socket);
console.log(500);
}
module.exports = onSearch;
and then
socket.on('search', search(socket));
CodePudding user response:
Besides the above approach, if you want to avoid creating wrapper functions one thing you can do is simply create non arrow functions and make use of this
.
// onConnection method which attaches listeners
//socket is available here
const onConnection = async (socket) => {
...
socket.on('search', metasearch);
...
}
function metasearch (args) {
console.log(this.id);
};