Stoimen
Stoimen

Reputation: 669

How to emit an event and pass a function as a parameter with socket.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)?

Upvotes: 1

Views: 9789

Answers (2)

Ito
Ito

Reputation: 2167

You can serialize your function, maybe it's a dangerous way for some functions. But socket.io transfers only strings as pure strings or JSON. You can try to eval string function when receive it from server side.

NOTE: Code not tested below:

function hello() {
  return "Hello Cruel World";
}

socket.emit('send-function', { myFunc : hello.toString() });

...

on server side:

socket.on('send-function', data) {
  console.log(eval(data.myFunc));
} 

Try on this code and give us a feedback if it works.

Upvotes: 0

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

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(){
    // ...
})

Upvotes: 4

Related Questions