1
Vote

CallFunction only handles Global functions

description

I tried wrapping functions into it's own namespace and CallFunction appears to not like it. I get a null exception when doing it this way.

Example

jint.Run(@" var MyClass = {
EpicFail: function() {
 return 1;
}
}
");

jint.CallFunction("MyClass.EpicFail")

comments

jtrahan wrote Jun 26, 2012 at 11:24 AM

I figured out a way around it for the time being. I wrote a wrapper function to find the function so it can be called with CallFunction.
    private JsFunction FindFunction(string name)
    {
        var context = ((JsObject) jint.Global);
        var keys = name.Split('.');
        for (var i = 0; i < keys.Length; i++)
        {
            if (context == null || context is JsUndefined) return null;
            context = (JsObject) context[keys[i]];
            if (i != keys.Length - 1) continue;
            if (!(context is JsFunction)) return null;
        }

        return (JsFunction)context;
    }
example:
var f = FindFunction("A.B.C.D")
if (f != null) jint.CallFunction(f);

jtrahan wrote Jun 26, 2012 at 1:42 PM

Grr actually this doesn't work properly. Even though I pass the Function to callfunction it appears that if there are inner functions within it it won't call it.

jtrahan wrote Jun 28, 2012 at 2:33 PM

So here is a workaround.

Add this to your core scripts

function __applyFunctionByName(functionName) {
var args = Array.prototype.slice.call(arguments, 1);
var context = this;
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) context = context[namespaces[i]];
return context[func].apply(context, args);
}

then you can call

jint.CallFunction("__applyFunctionByName", "MyClass.FuncName", arg1, arg2, etc)