Silverlight alpha: handling SL object''s events from Javascript code

You have several options for handling events fired by your SL objects in javascript. The first option is to hook up the event from Javascript code. In this scenario, you”ll probably start by hooking up the onLoad event of the Silverlight control:

function createSilverlight() {
  Sys.Silverlight.createObjectEx({
       source: “Page.xaml”,
       parentElement: document.getElementById(“SilverlightControlHost”),
       id: “SilverlightControl”,
       properties: {
          width: “100%”,
          height: “100%”,
          version: “0.95”,
          enableHtmlAccess: true
       },
       events: {
           onLoad:handleLoad}
       });
}

Then, from the handleLoad method, you”ll write the code for hooking up the required event:

function handleLoad(sender){
     sender.Content.FindName( “r” ).addEventListener( “MouseLeftButtonDown”, “h” );
}

In the previous example,I start by getting a reference to an element (named r) and hook up the MouseLeftButtonDown event through the addEventListener method. It”s interesting to note that by using the addEventListener method,you can hook up several methods with the same event (ie, it”s possible to have several methods that handle the same event and they”ll all be called when that event is generated). Oh, and if you”ve set up an event handler from managed code, it”ll also be called when the event fires.

There”s another option available: you can do it from the XAML by using the Javascript: prefix. I”m not sure if this is a recommended approach, but it works. Lets walk through an example. When we have this:

<Rectangle x:Name=”r” Width=”66″ Height=”80″ 
             Canvas.Left=”41″ Canvas.Top=”40.537″
             Fill=”red” MouseLeftButtonDown=”h” />

we”re saying that there”s an h method in your codebehind file that handles the event. When you”re using the 1.0 version, this means that the platform expects to find a Javascript method called h. However, when using the 1.1 version, it has a different meaning: in this case, you”re supposed to have a managed method (ie, a method written in managed code) in your code-behind file. 

The interesting part is that if you use the javascript: prefix, it”ll search for a Javascript h method:

MouseLeftButtonDown=”javascript : h” (remove the space)

As I”ve said, I”m not sure if this is the intended usage, but it works…

Advertisements

~ by Luis Abreu on June 14, 2007.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: