views:

394

answers:

2

The HtmlObject provides all the necessary functionality to register managed event handlers for script and DOM events, but what if the class you need to listen to doesn't exist as a DOM element, but a scripting variable (referenced via ScriptObject) instead?

A: 

A javascript object doesn't support the concept of attached events. However it may support the concept of a property holding a reference to function that if assigned will be called at a certain point.

I take you have such an object?

If so you use the ScriptObject SetProperty method using the name of the property that should hold a reference to a function and a delegate to Managed method matches the signature that the Javascript object will call.

Caveat the following is untested at this point but should put you on the right path.

//Javascript in web page.
var myObj = new Thing();

function Thing()
{
     this.doStuff = function()
     {
         if (this.onstuff) this.onstuff("Hello World");
     }
}

// C# code in a Silverlight app.

class SomeClass
{
    private ScriptObject myObject;
    public SomeClass(ScriptObject theObject)
    {
         myObject = theObject;
         myObject.SetProperty("onstuff", (Action<string>)onstuff);
    } 

    function void onstuff(string message)
    {
         //Do something with message
    }

}
AnthonyWJones
A: 

As stated by AnthonyWJones, Silverlight can't attached to JavaScript events. The right thing to do in this situation is to do the following:

Enable scripting access in Silverlight:

  1. Mark the class with the ScriptableType attribute, or mark the specific methods with ScriptableMember
  2. Call HtmlPage.RegisterScriptableObject in the constructor.

Once everything is set up in the Silverlight code, here's what you do in JavaScript:

  1. Obtain a reference to the JavaScript object and register an event handler
  2. Use document.getElementById to get the Silverlight control
  3. Call .Content.. in the JavaScript event handler. For example, silverlight.Content.Page.UpdateText(text).

So basically, all event handling is performed in JavaScript, but the JavaScript event handlers can be used to call functions in Silverlight.

Adrian Anttila