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

New Post: Call JS function with object as parameter

$
0
0
Greetings!

There a several ways to go here. Suppose you have a JavaScript function that takes such an object:
engine.AddHostType(typeof(Console));
engine.Execute(@"
    function foo(arg) {
        Console.WriteLine(arg['a.b']);
        Console.WriteLine(arg['foo.bar']);
    }
");
You can use a dynamic .NET object for the argument:
IDictionary<string, object> arg = new ExpandoObject();
arg["a.b"] = 123;
arg["foo.bar"] = 456;
engine.Script.foo(arg);
Another possibility is to use ClearScript's PropertyBag class:
var arg = new PropertyBag();
arg["a.b"] = 123;
arg["foo.bar"] = 456;
engine.Script.foo(arg);
A third option is simply to use a script object:
dynamic arg = engine.Evaluate("({})");
arg["a.b"] = 123;
arg["foo.bar"] = 456;
engine.Script.foo(arg);
Keep in mind though that if the argument is a large dictionary with hundreds of elements, then JSON tunneling, as clunky as it is, could provide better performance, as it minimizes the number of dynamic calls and objects flowing across the host-script boundary.

Good luck!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images