Skip to content Skip to sidebar Skip to footer

How To Pass Function To Client From Node.js Server

All: What I want to do is like: On Node server side: var fn = function(){ alert('hello'); } I want to send this function to client side(currently using AngularJS, but it does

Solution 1:

So, something like this:

// 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]();

Solution 2:

Here's a plunk.

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

function getFunction(textReceived) {
  eval(textReceived);
  return fn;
}

var f = getFunction(textReceived);

f();

Post a Comment for "How To Pass Function To Client From Node.js Server"