Code Preview of Generic Object Embedding
I gave some screenshots and a description in an earlier post of what I called "generic object embedding". I've since forked this functionality into a "development" codebase because this aspect of spidermonkey-dotnet is still volatile. Release 0.2.0 [codeplex.com] is available, which also includes a javascript shell implemented with this new technique.
Now let's take a look at our friend the Customer object refactored and with a few attributes added to the methods we want to embed:
Now the only code needed to embed this object is the following line:
JSEmbedder.JSObjectInitialize(cxPtr, globPtr, IntPtr.Zero, typeof(Customer), true);
Here's a screenshot of the shell enabled with the Customer object:
Now let's take a look at our friend the Customer object refactored and with a few attributes added to the methods we want to embed:
public class Customer
{
private int m_age;
private string m_name;
[JSMember()]
public int Age
{
get { return m_age; }
set { m_age = value; }
}
[JSMember()]
public string Name
{
get { return m_name; }
set { m_name = value; }
}
[JSMember()]
public void SetName(string newName)
{
m_name = newName;
}
[JSMember()]
public int ComputeReduction()
{
if (m_age < 25)
return 10;
else
return 5;
}
}
Now the only code needed to embed this object is the following line:
JSEmbedder.JSObjectInitialize(cxPtr, globPtr, IntPtr.Zero, typeof(Customer), true);
Here's a screenshot of the shell enabled with the Customer object:
3 Comments:
You very good code.
It would be really cool, if you could have an option that would simply make all public methods/properties available (including static ones)... that would be awesome... Also, what about embedding an already instantiated object into the javascript context? ex: a "User" object that could represent the current user in the environment, or something similar...
This example was really just to get the idea across. At this point the GibberMonkey project demonstrates what you're asking for and much more. Here is some code from its initialization. First you see the embedding of every Type from the IrcClient library. Then, an already instantiated a bot/irc client object (here: irc) is assigned as a named property of the global object. That property behaves as the window or document objects of the JS DOM.
Type[] ts = System.Reflection.Assembly.GetAssembly(typeof(IrcClient)).GetTypes();
foreach (Type t in ts)
{
JSEmbedder.JSObjectInitialize(cxPtr, globPtr, IntPtr.Zero, t, false);
}
JSEmbedder.JSObjectInitialize(cxPtr, globPtr, IntPtr.Zero, typeof(EventArgs), false);
IntPtr p = JSEmbedder.JSObjectCreate(cxPtr, irc);
JS.JS_DefineProperty(cxPtr, globPtr, "client", JS.OBJECT_TO_JSVAL(p), null, null, 0);
Post a Comment
Links to this post:
Create a Link
<< Home