Access JavaScript objects from Host

Mar 24, 2013 at 2:45 PM
Hello,

I am really impressed by your work :) While playing a litte around with ClearScript I got a question concerning the following scenario, where I want to pass JavaScript objects to the host:

C#:
   public void Obj.TestMethod(dynamic o)
   {
      // I want to inspect with o here
   }

JS: 
  Obj.TestMethod( { a:"foo", b:"bar", c: {d:3 } })
In the host I can dynamically access all properties of o, like "o.a" as expected. But it would very nice if I could access o like via PropertyBag or Dictionary<string, object> interface to be able to explore the object given as argument.
(I already tested GetDynamicMemberNames of the DynamicMetaObject - but it was empty)

Is there a way to inspect the argument from the host?

Thanks,

-Karl
Coordinator
Mar 25, 2013 at 12:01 AM
Edited Aug 3, 2013 at 3:28 AM
Hi Karl,

Thanks for your kind words.

You're quite right that script objects in ClearScript currently do not override DynamicObject.GetDynamicMemberNames(), and the system's default implementation returns only an empty array. This is a bug that we'll fix shortly.

In the meantime, if you wish to explore a script object, you can always leverage the script engine:
// C#
dynamic forEachProp = engine.Evaluate(@"
    (function (obj, callback)
    {
        for (var propName in obj)
            callback(propName);
    })
");
[...]
public void TestMethod(object o)
{
    forEachProp(o, new Action<string>(propName =>
    {
        Console.WriteLine(propName);
    }));
}
Coordinator
Mar 25, 2013 at 2:43 PM
Edited Aug 3, 2013 at 3:28 AM
Hi again!

Here's an alternative:
// C#
engine.Execute(@"
    function getPropNames(obj, list)
    {
        for (var propName in obj)
            list.Add(propName);
    }
");
[...]
public void TestMethod(object o)
{
    var list = new List<string>();
    engine.Script.getPropNames(o, list);
    foreach (var propName in list) {
        Console.WriteLine(propName);
    }
}
As you can see, there are lots of ways to do it. The host and the script engine can work together!
Mar 26, 2013 at 9:55 AM
Right! The way things are integrated into each other are very mighty :)

Thanks a lot!