通过socket.io发送匿名函数? [英] Sending anonymous functions through socket.io?

查看:106
本文介绍了通过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定义一个commands对象,然后只需传递一个commandName:

What you can do instead is to define a commands object with the functions 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆