Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

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

0
0
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:
publicclass Page {
    publicvoid 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:
publicclass Page {
    publicvoid 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!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images