Running managed JavaScript in Silverlight

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:

<Canvas x:Name="root" Width="500" Height="500"
 xmlns="http://schemas.microsoft.com/client/2007"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
  <Canvas x:Name="loadingHelper" Loaded="OnLoaded" />
  <TextBlock Canvas.Top="10px" x:Name="text1" Width="400" />
</Canvas>

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:

<x:Code Source="test.jsx" Type="text/jscript" />

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.

Import("System.*");

function OnLoaded(sender, args) {
    // add your code here
}

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:

text1.Text = new Date().toString();

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.

3 Comments

Comments have been disabled for this content.