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 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
var events = ['first_event', 'second_event', 'third_event'];
for (var i in events)
(function(e) {
socket.on(e, function(data) {
console.log(e); // You have access to the event name
client.emit(e, data); // Relay to client
});
})(events[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With