Gatsbill Gatsbill - 1 month ago 9
Javascript Question

in socket.on callback get name of listener in the socket object

Where can i find the socket listener name in the socket object ?

Example :

socket.on('test', function(data) {
// is there a property of socket object that is equal to 'test' ?
})


EDIT: I want this because my listeners and my callbacks are in different files and I don't want to copy the listener name by hands.

socketController with listeners :

'use strict';

const onSendMessage = require('./message/send');
const onGetMessages = require('./message/get');
const onAskFriend = require('./friends/ask');
const onAcceptFriend = require('./friends/accept');
const onRemoveFriend = require('./friends/remove');
const onGetFriends = require('./friends/get');

module.exports = (socket) => {

// message
listenTo(socket, 'sendMessage', onSendMessage);
listenTo(socket, 'getMessages', onGetMessages);

// friends
listenTo(socket, 'getFriends', onGetFriends);
listenTo(socket, 'askFriend', onAskFriend);
listenTo(socket, 'acceptFriend', onAcceptFriend);
listenTo(socket, 'removeFriend', onRemoveFriend);

};

function listenTo(socket, name, callback) {
socket.on(name, data => callback(socket, data));
}


socket getFriends :

'use strict';

const db = require('../../database/mongo').collections;
const ObjectID = require('mongodb').ObjectID;

module.exports = (socket) => {

const query = {
ownerid: ObjectID(socket.id)
}

db.friends.find(query).toArray((err, friends) => {

if (err) {
return socket.emit('getFriends', {status: 500});
}

socket.emit('getFriends', {status: 200, body: friends});

});

};


I don't like writing
socket.emit('getFriends')
by hands each time, it can be error prone.

Answer

I don't knwow if you can do this (I think no) but why not simply:

function listenTo(socket, name, callback) {
    socket.on(name, data => callback(socket, name, data));
}

and :

module.exports = (socket, message) => {

   const query = {
      ownerid: ObjectID(socket.id)
   }

   db.friends.find(query).toArray((err, friends) => {

      if (err) {
         return socket.emit(message, {status: 500});
      }

      socket.emit(message, {status: 200, body: friends});

   });

};