Calling javascript methods from your Silverligh app
Well, sort of. To be able to do this, there are some prerequisites:
- The Canvas type must be annotated with the ScriptableAttribute;
- You must expose an event which the js code on the page should handle;
- You must register your control with the WebApplication object by calling the RegisterScriptableObject method.
Here's a quick example (just the important parts):
[Scriptable]
public partial class Demo: Canvas{
public void Page_Loaded( object o, EventArgs e ){
InitializeComponent();
//register this object so that it's accessible from JS
WebApplication.Current.RegisterScriptableObject( "Managed", this );
}
[Scriptable]
public event EventHandler SomethingHappened;
//more code
}
Now, on your html page, you can handle the Load event of the Silverlight control so that you can hook up the SomethingHappened event with a custom js method:
function handleLoad( sender, e ){
sender.Content.Managed.SomethingHappened = myMethod; //myMethod is a js function
}
function myMethod( sender, e ){
}
And that's it (i didn't show the code for firing the event because it's just like you do in traditionat .NET programming).
Notice how the name used during the registration is "added" by the Silverlight control to the Content property, letting you access all the ScriptableAttribute annotated elements from js code...
Btw, do note that besides events, you can also expose other elements from your Silverlight types (which I'll talk in a future post). Still regarding the events, you can also use a custom EventArgs type and it'll get passed to the js method. When you do this, you should also annotate your custom EventArgs class with the ScriptableAttribute and make sure that all the elements that you want to use from js are of type int, double, string or ScriptableObject (complex types should be serialized into JSON and passed as strings). If you don't follow these rules, you'll get an exception during the RegisterScriptableObject method call.