This project has moved and is read-only. For the latest updates, please go here.

Passing Action/Func into JS?

Apr 17, 2015 at 10: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 18, 2015 at 12:02 AM

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 5: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 1: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!