通过socket.io发送匿名函数? [英] Sending anonymous functions through socket.io?
问题描述
我想创建一个客户端函数,它可以使用客户端变量接收和执行任意命令.我将从我的服务器发送这些函数,方法是使用 socket.io 发送一个包含匿名函数的 JSON 对象,这将是我的命令.它看起来像下面这样:
I want to create a client-side function that can receive and execute arbitrary commands using client-side variables. I will be sending these functions from my server by using socket.io to send a JSON object containing an anonymous function which will be my command. It looks something like the following:
//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);
}});
然而,当我尝试时,客户端收到一个空的 json 对象(data == {}
),然后抛出异常,因为数据不包含执行方法.这里出了什么问题?
Yet, when I tried it out, the client side received an empty json object (data == {}
), then threw an exception because data contained no method execute. What is going wrong here?
推荐答案
JSON 不支持包含 function
定义/表达式.
JSON doesn't support the inclusion of function
definitions/expressions.
你可以做的是用你需要的function
s定义一个commands
对象,然后传递一个commandName
:
What you can do instead is to define a commands
object with the function
s you need and just pass a 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' });
您也可以使用 fn.apply()
传递参数并检查 commandName
是否与带有 in
:
You can also use fn.apply()
to pass arguments and check the commandName
matches a 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' ]
});
这篇关于通过socket.io发送匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!