I am building an intermediate node server which acts as both socket client and server, I want to listen to backend server events and then forward the events to client(browser) after processing.
var socket = require('socket.io'),
client = require('socket.io-client');
socket.on('event_name', function(data) {
/* Logic to process response and relay to client */
client.emit(this.event, data); // How can I get name of the outer event?
});
I want to get the event_name
value in the callback. How can I do?
I am building an intermediate node server which acts as both socket client and server, I want to listen to backend server events and then forward the events to client(browser) after processing.
var socket = require('socket.io'),
client = require('socket.io-client');
socket.on('event_name', function(data) {
/* Logic to process response and relay to client */
client.emit(this.event, data); // How can I get name of the outer event?
});
I want to get the event_name
value in the callback. How can I do?
3 Answers
Reset to default 8I am not sure if you can get event name from the callback, but you can workaround it.
var socket = require('socket.io');
function registerEvent(eventName, cb) {
socket.on(eventName, function () {
var args = [].slice.apply(arguments);
args.unshift(eventName);
cb.apply(null, args);
});
}
registerEvent('my_event', function (eventName, data) {
// now you can access event name
// it is prepended to arguments
console.log('Event name', eventName);
});
You could try something similar :
// List of events relayed to client
const events = ['first_event', 'second_event', 'third_event'];
for (const event of events)
socket.on(event, function(data) {
console.log(event); // You have access to the event name
client.emit(e, data); // Relay to client
});
};
Since version 3.x, you can use middlewares, like this :
io.on("connection", socket => {
socket.use(([event], next) => {
socket.event = event;
next();
});
socket.on("myevent", (data) => {
console.log(socket.event); // Will print "myevent" in that case
});
});