Call JS function with object as parameter

Mar 15, 2016 at 8:50 AM
Hi,

I need to call a function in my Javascript which takes a Javascript object as parameter. The catch is that the property names of the object are something like "a.b" or "foo.bar" and they are dynamic, so I cannot create a static object to call with.

Is there any way to call the function with a Dictionary<string, object> and have it converted to a Javascript object automatically?

So far I've done a workaround:
  1. Create the Dictionary<string, object>, add values
  2. Convert it to JSON
  3. Call the Javascript function
  4. In the function use JSON.parse to turn it into a Javascript object
It works, but it's clunky.

Thanks a lot!
Coordinator
Mar 15, 2016 at 2:21 PM
Edited Mar 17, 2016 at 1:21 PM
Greetings!

There are 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!
Mar 17, 2016 at 1:33 PM
Thanks for the answer. I'll stick with the JSON tunneling then, as I do need performance.