Sending anonymous functions through socket.io?

前端 未结 2 1609
日久生厌
日久生厌 2020-12-18 10:42

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 usin

相关标签:
2条回答
  • 2020-12-18 11:21

    JSON doesn't support the inclusion of function definitions/expressions.

    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' });
    

    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' ]
    });
    
    0 讨论(0)
  • 2020-12-18 11:27

    You can't send literal JavaScript functions and expect it to work. You'll need to stringify the function first (i.e put it within a set of quotes), then eval the string on the client side.

    0 讨论(0)
提交回复
热议问题