如何将函数从 Node.js 服务器传递给客户端

How to pass function to client from Node.js server

本文关键字:服务器 客户端 js Node 函数      更新时间:2023-09-26

All:

我想做的是:

在节点服务器端:

var fn = function(){
    alert("hello");
}

我想将这个函数发送到客户端(目前使用AngularJS,但只要可以解决这个问题就没关系),并将其绑定到按钮单击事件。因此,单击该按钮时,我可以弹出警报窗口。

谢谢

所以,像这样:

// Predefined functions
var allowedFunctions = {
    'f1': function () {alert('Called f1');},
    'f2': function () {alert('Called f2');},
    'f3': function () {alert('Called f3');},
};
// This comes from the server
var callThisOne = 'f2';
// Here's how you call it now
allowedFunctions[callThisOne]();

这是一个扑通

// Get this from the server
var textReceived = 'var fn = function(){ alert("hello"); };';
function getFunction(textReceived) {
  eval(textReceived);
  return fn;
}
var f = getFunction(textReceived);
f();