views:

35

answers:

1

I'm calling out to javascript from a SL component using the HtmlPage.Window.Invoke api, when I call a javascript function defined in the page (html) it executes as expected, e.g.

HtmlPage.Window.Invoke("publishValue", topic, jsonObject);

But when I place the javascript function in a *.js file it is failing to execute the method even though the *.js file has been loaded into the DOM, so the following fails with an invoke exception.

HtmlPage.Window.Invoke("FrameworkEventBroker.publishFrameworkEvent", topic, jsonObject);

Any ideas why this is happening?

Cheers

AWC

+1  A: 

The problem isn't with the (*.js), it fails when calling methods not directly attached to the window instance.

A workaround would be to register your methods to the window object. To simplify this I created a JavaScript helper as follows:

<script type="text/javascript">
function createDelegate(instance, method) {
    return function () {
        return method.apply(instance, arguments);
    }
}
function registerBroker(prefix, brokerInstance) {
    for (var prop in brokerInstance)
        //uncomment the IF statement to only include properties 
        //starting with upper case letter.
        //if (prop.charAt(0) >= 'A' && prop.charAt(0) <= 'Z') 
             eval("window."+prefix+"_" + prop + "= createDelegate(brokerInstance, brokerInstance[prop]);");
}
</script> 

Then you simply invoke broker methods as:

HtmlPage.Window.Invoke(
          string.Format("{0}_{1}", PREFIX, METHOD_NAME), Args);

That's it.

Example :

<script type="text/javascript">
    var broker = new FrameworkEventBroker();
    registerBroker("FrameworkEventBroker",broker);
</script>

and from silverlight:

HtmlPage.Window.Invoke("FrameworkEventBroker_publishFrameworkEvent", topic, jsonObject);

UPDATE

I added the createDelegate helper to maintain a reference to the broker instance when called on the window object.

MK