JSON doesn't support the inclusion of function
definitions/expressions.
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' });
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' ]
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…