Time flies like an arrow in Script#

As kouPhax requested this on the Rx forum, I decided to post a port to Script# of the Time flies like an arrow sample that ships with Rx for JavaScript.

Rx for JavaScript already ships with a binding for Script#, so that will make our lives a lot easier (you can find the binding in <InstallPath>\Redist\ScriptSharp\RxJs.dll)

For this sample I'll assume you have Script# 0.5.6.0 installed from Nikhil's Script# site.

We start off with creating a Script# enabled website:

image

Next we open the Scriplet editor for the default Scriplet in the project:

image

We’ll make Script# aware of Rx by adding a reference to the RxJS.Dll:

image

As well as the rx.js JavaScript file

image

Next we’ll add the container div to the body of the Html page:

<div id="container"></div>

Now it is time to do some coding:

using

System;
using System.DHTML;
using ScriptFX;
using ScriptFX.UI;
using Rx;
public class MyScriptlet
{
public static void Main(ScriptletArguments arguments)
{
DOMDocument document = Window.Document;
Observable mouseMove = Observable.FromHtmlEvent(document, "mousemove");
string text = "time flies like an arrow";
DOMElement container = document.GetElementById("container");
for (int i = 0; i < text.Length; i++)
{
ActionInt32 closure = delegate (int j)
{
DOMElement s = document.CreateElement("span");
s.InnerHTML = text.CharAt(j).ToString();
s.Style.Position = "absolute";
container.AppendChild(s);
mouseMove.Delay(j * 100).Subscribe(delegate(object o)
{
Event mouseEvent = (Event)o;
s.Style.Top = mouseEvent.OffsetY + "px";
s.Style.Left = mouseEvent.OffsetX + j * 10 + 15 + "px";
});
};
closure(i);
        }
}
}

As you can see the code looks very similar to the JavaScript version, just adding a few types. One of the interesting things is that just like in the JavaScript version, you’ll need to put a manual closure inside the for loop. The reason for this is that Script# gives you C# syntax, but maintains JavaScript semantics.

There you have it, your first Rx Script# app. Any feedback on Rx for Script# is of course welcome on the Rx forum