Get event name in io socket event callback function

I create an intermediate node server that acts as a client and socket server, I want to listen to server server events and then forward events to the 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 value of event_name in a callback. How can i do

+6
source share
2 answers

You can try something like this:

 // 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]); 
+3
source

I'm not sure that you can get the event name from the callback, but you can get around 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); }); 
+6
source

Source: https://habr.com/ru/post/986129/


All Articles