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!

3
  • Can you explain more closely where the string "function(data){alert(data);}" comes from, exactly? Commented Sep 19, 2012 at 8:45
  • 1
    Does this help? (Using eval) Commented Sep 19, 2012 at 8: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. Commented Sep 19, 2012 at 8:51

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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)+");");

Comments

0

I think you are not correctly using the Function constructor. See this link for reference:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Reference%2FObjects%2FFunction#Example.3A_Specifying_arguments_with_the_Function_constructor

Comments

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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.