Is it possible to expose a JavaScript style function with a callback in clearscript

Jan 31, 2014 at 4:06 AM
Edited Jan 31, 2014 at 4:06 AM
I would like to expose an open method on my c# object that I am exposing to ClearScript. The open method signature would look like this
    public void open(string address, Action<dynamic> callback)
    {
        if (callback != null)
        {
            callback("success");
        }
    }
And calling it from script like this
page.open('http://www.cnn.com', function(status) { 
    // do somthing here with status
});
Coordinator
Jan 31, 2014 at 12:47 PM
Edited Jan 31, 2014 at 2:16 PM
Hello!

On the .NET side you can access JavaScript objects, including functions, using the dynamic keyword. For example, you can define your class like this:
public class Page {
    public void open(string address, dynamic callback) {
        if (callback != null) {
            callback("success");
        }
    }
}
and then use it like this:
engine.AddHostObject("page", new Page());
engine.AddHostType("Console", typeof(Console));
engine.Execute(@"
    page.open('http://www.cnn.com', function(status) {
        Console.WriteLine(status);
    });
");
You can also set up a .NET delegate that calls a script function. This makes it possible to plug script code into an existing API that doesn't use dynamic. For example, if your class is already defined like this:
public class Page {
    public void open(string address, Action<string> callback) {
        if (callback != null) {
            callback("success");
        }
    }
}
you can use it from script code like this:
engine.AddHostObject("page", new Page());
engine.AddHostType("Console", typeof(Console));
engine.AddHostType("OpenCallback", typeof(Action<string>));
engine.Execute(@"
    page.open('http://www.cnn.com', new OpenCallback(function(status) {
        Console.WriteLine(status);
    }));
");
Thanks for your question, and good luck!
Jan 31, 2014 at 6:32 PM
Perfect. That did the trick. Thanks