Ari*_*Ari 4 json anonymous-function node.js socket.io
我想创建一个客户端函数,可以使用客户端变量接收和执行任意命令.我将从我的服务器发送这些函数,使用socket.io发送一个包含匿名函数的JSON对象,这将是我的命令.它看起来像下面这样:
//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);
}});
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试它时,客户端收到一个空的json对象(data == {}),然后抛出异常,因为数据不包含方法执行.这里出了什么问题?
JSON不支持包含function定义/表达式.
你可以做的是commands用function你需要的s 定义一个对象,然后传递一个commandName:
// client-side
var commands = {
log: function (param) {
console.log(param);
}
};
socket.on('executecommand', function(data){
var a = 'foo';
commands[data.commandName](a);
});
Run Code Online (Sandbox Code Playgroud)
// server-side
socket.emit('executecommand', { commandName: 'log' });
Run Code Online (Sandbox Code Playgroud)
您还可以使用fn.apply()传递参数并检查commandName匹配命令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);
}
});
Run Code Online (Sandbox Code Playgroud)
// server-side
socket.emit('executecommand', {
commandName: 'log',
arguments: [ 'foo' ]
});
Run Code Online (Sandbox Code Playgroud)