Passing Action/Func into JS?

Apr 17, 2015 at 9:30 PM
I am trying to pass a C# delegate/Func/Action as a parameter to a Javascript function (on('event',handler)). Right now, the thing that shows up in the JS side is not a function. What is the expected implementation of a function like this?
function myJsFunction(callback) {
scriptObject.myJsFunction(new Action(() => { /* YAY IT WORKED */ });
Apr 17, 2015 at 11:02 PM

What you're doing should work. The delegate may not appear to be a JavaScript function (that is, the typeof operator would return "object" rather than "function"), but it should be invocable just like a function.

For example, this code prints "Hello!" as expected:
engine.Execute("function foo(x) { x(); }"); Action(() => Console.WriteLine("Hello!")));
Are you doing something differently?

Apr 29, 2015 at 4:16 AM
Thanks - no I'm doing that. But the problem is I'm passing it to EventEmitter's on() method, which throws if it's not a function. So I guess I'll write a wrapper of some sort. Hopefully apply works...
May 11, 2015 at 12:07 PM
Hi again,

If you're using V8, consider upgrading to the just-released ClearScript 5.4.2, which provides a new toFunction method for delegates. This method creates a native JavaScript function that invokes the delegate:
engine.Script.onEvent = new Action<object>(arg => DoSomething(arg));
engine.Execute("eventSource.on('someEvent', onEvent.toFunction())");
This feature might be useful in situations where library code validates functions via typeof or toString().

Good luck!