Node.js – How to emit an event and pass a function as a parameter with socket.io

node.jssocket.io

I am using socket.io and I am trying to emit an event from my server and pass an object with a function as a parameter. Here is my code:

  socket.emit('customEvent', {
    name : "Test".
    myFunc : function() {
        //some logic here
    }
  });

and then in the client (my app in the browser) I am able to access 'name' property but when I try to access 'myFunc' but I get 'undefined' for it. Here is my code

socket.on('customEvent', function(data){
    data.myFunc();
});

What is the correct approach for this (if it is possible at all)?

Best Answer

The data is transmitted as JSON, so it can't contain functions. Maybe you're looking for what's called 'acknowledgments' in socket.io's documentation?

// server
socket.on('customEvent', function (data, fn) {
    fn(data.x)
})

// client
socket.emit('customEvent', { x: 1 }, function(){
    // ...
})