2

I need to call a user defined javascript function from within my costom jquery plugin and pass parameters to it, for example:

function test(data)
    {
      var myfunc="function(data){alert(data);}"; //this is user defined function I   retrieved from html tag attribute
      var fn=new Function("("+myfunc+")();");
      fn.apply(this,arguments);
      return fn;
} 
test("hello");

The result is undefined, how can I pass data parameter from test function to user defined function? thanks in advance!

question update:

I'm writing a jquery plugin to handle ajax request, much like asp.net mvc unobtrusive ajax, I get the ajax callfack function from html tag attrbute, for example:

<div data-ajax-success="function(data,status,xhr){alert(data);}"....

the value of data-ajax-success attribute is user defined function, it can be following formats:

data-ajax-success="function(data,status,xhr){alert(data);}"
data-ajax-success="function(data){alert(data);}"
data-ajax-success="function(){alert('hello');}"
data-ajax-success="functionName"

I need to parse this attribute value as javascript function and pass jquery ajax callback parameters to this function, where data-ajax-success value is function name, I could call it correctly using following method defined in Micrsoft jquery-unobtrusive-ajax.js:

function getFunction(code, argNames) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) {
            fn = fn[parts.shift()];
        }
        if (typeof (fn) === "function") {
            return fn;
        }
        argNames.push(code);
        return Function.constructor.apply(null, argNames);
    }

but when data-ajax-success is function body, I could not pass parameter to it, here's my sample code that handle ajax callback:

loadData: function (index, options) {
complete: function (xhr,status) {
            $(context.loading).hide(context.loadingDuration);
            getFunction(context.onComplete, ["xhr", "status"]).apply(this, arguments);
            },
        success:function (data, status, xhr) {
            $(context.updateTarget).html(data);
            getFunction(context.onSuccess, ["data", "status", "xhr"]).apply(this, arguments);
            },
            error: getFunction(context.onFailure, ["xhr", "status", "error"])
});

      $.ajax(options);
  }

anyone can help me? thank you very much!

ibtarek
  • 795
  • 4
  • 16
Webdiyer
  • 19
  • 1
  • 6
  • Can you explain more closely where the string `"function(data){alert(data);}"` comes from, exactly? – Tomalak Sep 19 '12 at 08:45
  • 1
    Does [this](http://stackoverflow.com/questions/2060634/jquery-string-to-function-convert) help? (Using `eval`) – keyser Sep 19 '12 at 08:47
  • 1
    Can I please be the first to point out that overall, this looks like a very bad idea and you're probably doing it wrong. – nickf Sep 19 '12 at 08:51

5 Answers5

2

MDN describes the syntax of the Function object like this:

new Function ([arg1[, arg2[, ... argN]],] functionBody)

Here is the corresponding example:

// Example can be run directly in your JavaScript console

// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// > 8

Applied to your example code it should read:

var fn=new Function("data",myfunc);

Reference:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function

Gung Foo
  • 13,392
  • 5
  • 31
  • 39
0

You are not passing an argument to the fn function.

Change this part:

var fn=new Function("("+myfunc+")();");

to this:

var fn=new Function("("+myfunc+")("+data+");");

But if you are defining the function like that the data variable must contain a json string:

var fn=new Function("("+myfunc+")("+JSON.stringify(data)+");");
timidboy
  • 1,702
  • 1
  • 16
  • 27
0

Please check this

<!DOCTYPE html>
<html>
<body>

<p>Setting a default value to a function parameter.</p>
<p id="demo"></p>

<script>
function test(content)
    {
    const funString = `(function(content){return content})(content)`
    var adder = eval(funString);
   

// Call the function
return adder;
    
     
} 

document.getElementById("demo").innerHTML = test(2);
</script>

</body>
</html>
Abhay Phougat
  • 280
  • 2
  • 6
-1

I solved it by modifying this microsoft method:

  function getFunction(code, argNames) {
    var fn = window, parts = (code || "").split(".");
    while (fn && parts.length) { fn = fn[parts.shift()]; }
    if (typeof (fn) === "function") { return fn; } //onSuccess="functionName"
    if ($.trim(code).toLowerCase().indexOf("function")==0) { return new Function("return (" + code + ").apply(this,arguments);");} //onSuccess="function(data){alert(data);}"
    argNames.push(code);
    try {return Function.constructor.apply(null, argNames); //onSuccess="alert('hello');return false;"
    }catch(e){alert("Error:\r\n"+code + "\r\nis not a valid callback function");}
}
Webdiyer
  • 19
  • 1
  • 6