Running managed JavaScript in Silverlight

Michael Schwarz on Thursday, May 31, 2007

At MIX 07 Jim Hugunin announced a new level of support for dynamic languages on .NET that they're calling the DLR (Dynamic Language Runtime). With Silverlight 1.1 you get support for dynamic languages today: Phyton, JavaScript (EcmaScript 3.0), Visual Basic and Ruby.

Today I will show you how to run a simple JavaScript inside the DLR.

What you need?

First you have to download the Silverlight 1.1 plugin. This software is currently in alpha and it is available for Mac and Windows. Everything else we can write in notepad.exe or any other text editor.

A very example managed JavaScript

The first example will write the current time to a XAML TextBlock. For this I have created a small test.xaml file with following content:

<pre class="csharpcode">&lt;Canvas x:Name=<span class="str">"root"</span> Width=<span class="str">"500"</span> Height=<span class="str">"500"</span>
xmlns=<span class="str">""</span>
xmlns:x=<span class="str">""</span>
&lt;Canvas x:Name=<span class="str">"loadingHelper"</span> Loaded=<span class="str">"OnLoaded"</span> /&gt;
&lt;TextBlock Canvas.Top=<span class="str">"10px"</span> x:Name=<span class="str">"text1"</span> Width=<span class="str">"400"</span> /&gt;

Next I will add the source code for the managed JavaScript. I have decided to place all the content in a seperate file called test.jsx (I think this will be the default file extension for managed JavaScript).

To include the file we have to add following XAML tag to our test.xaml:

<pre class="csharpcode">&lt;x:Code Source=<span class="str">"test.jsx"</span> Type=<span class="str">"text/jscript"</span> /&gt;</pre>

Ok, next we will create the test.jsx to write the current time to the TextBlock element named text1. You may have noticed that I put a loading helper with the Loaded event configured to run OnLoaded. This method you have to declare in your managaed JavaScript file.

<pre class="csharpcode">Import(<span class="str">"System.*"</span>);

function OnLoaded(sender, args) { <span class="rem">// add your code here</span> }</pre>

All XAML elements you put in the XAML file are accessible with their name, so you don't have to use something like FindElement or GetElementById. Simple call following line and the date will be displayed in the TextBlock:

<pre class="csharpcode">text1.Text = <span class="kwrd">new</span> Date().toString();</pre>

If you open the XAML file in a Silverlight container (using Silverlight.js and Sys.Silverlight.createObject) you will see a similar output like this:

Download the example here [1].