Sending anonymous functions over socket.io?
I want to create a client function that can accept and execute arbitrary commands using client side variables. I will send these functions from my server using socket.io to send a JSON object containing an anonymous function that will be my command. It looks something like this:
//client side
socket.on('executecommand', function(data){
var a = "foo";
data.execute(a); //should produce "foo"
});
//server side
socket.emit('executecommand', {'execute': function(param){
console.log(param);
}});
However, when I tried this, the client side received an empty json object ( data == {}
) and then threw an exception as the data did not contain any method. What's wrong here?
source to share
JSON does not support including definitions / expressions function
.
Instead, you can define the commands
c object function
you want and simply pass commandName
:
// client-side
var commands = {
log: function (param) {
console.log(param);
}
};
socket.on('executecommand', function(data){
var a = 'foo';
commands[data.commandName](a);
});
// server-side
socket.emit('executecommand', { commandName: 'log' });
You can also use fn.apply()
to pass arguments and check what commandName
matches the command with in
:
// client-side
var commands = { /* ... */ };
socket.on('executecommand', function(data){
if (data.commandName in commands) {
commands[data.commandName].apply(null, data.arguments || []);
} else {
console.error('Unrecognized command', data.commandName);
}
});
// server-side
socket.emit('executecommand', {
commandName: 'log',
arguments: [ 'foo' ]
});
source to share