Silverlight: When should you use RegisterScriptableObject?

.NET, Silverlight, Technical stuff
See comments

One of the most exciting features of Silverlight 2.0 is its ability to let .NET and JavaScript communicate in a very direct way. JavaScript objects can call .NET methods directly, and register for .NET events.

On the .NET part, this needs a little preparation. There are two steps that you need to perform to enable JavaScript –> .NET communication:

  1. Register the object you want to script.
  2. Mark every scriptable member with the ScriptableAttribute.

The first step lets the web application know that some members must be prepared for JavaScript. Then, each Scriptable member will be fetched and prepared. For example:

[Scriptable]
public partial class Page : Canvas
{
  public void Page_Loaded(object o, EventArgs e)
  {
    InitializeComponent();
    WebApplication.Current.RegisterScriptableObject("MainRoot", this);
  }

  [Scriptable]
  public void DoSomething()
  {
    // Do something
  }
}

and:

gslb.SL.TestScriptable.prototype =
{
  handleOnLoad : function(control, userContext, rootElement)
  {
    this._control = control;
    // Set up communication with CLR (if needed)
    this._rootCanvas = this._control.content.MainRoot;
    this._rootCanvas.DoSomething();
  }
}

In the code above, we marked the main Canvas as scriptable, as well as the method DoSomething. Having taken care of registering the main canvas with the WebApplication, we can then access it in JavaScript under the name “MainRoot”, and we can call the C# method from the JavaScript code.

One thing is dangerous, however! If you decide to get rid of the method “DoSomething”, no scriptable members can be found anymore. In that case, the call to “RegisterScriptableObject” will throw an exception. Any code located after the call to RegisterScriptableObject will not be executed, and it’s pretty sure that the application will cease to work correctly. Unfortunately,the error message is not very clear:

Error message 1

If you decide to go on and debug, the error message is not much clearer:

Error message 2

The rule is simple, but one has to remember: You can register a Scriptable Object only if it has Scriptable members!!

Previous entry | Next blog entry

Comments for Silverlight: When should you use RegisterScriptableObject?