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