views:

27

answers:

2

I'd like to receive callbacks from Javascript code to my Silverlight host without using ScriptableAttribute. I've seen it done before, but I couldn't work out how they did it. Has anyone got any ideas? Thanks

+2  A: 

Simple enough use:-

 HtmlPage.Window.Invoke("someJavascriptFunc", "Hello", "World");

In the javascript in the page hosting the silverlight have:-

 function someJavascriptFunc(p1, p2)
 {
     alert(p1 + ' ' + p2);
 }

Edit: Ken is right the above is the wrong way round.

Lets say you have this function in Silverlight:-

string GetStuff(string name)
{
     return "Hello " + name;
}

You can now make this function available to javascript like this:-

HtmlPage.Window.SetProperty("sayHello", new Func<string, string>(GetStuff));    

Now code in javascript can simply do something like this:-

alert(sayHello("Fred"));
AnthonyWJones
That's the opposite direction, I think: from SL to JS. I think he wants the other way, from JS to SL.
Ken Smith
@Ken: you're right d'oh!
AnthonyWJones
I hadn't seen that technique before. Nice.
Ken Smith
A: 

If you're using events, in theory, you can use AttachEvent to subscribe to events. That's not quite the same thing as callbacks, but it's close.

Caveats: I haven't tested AttachEvent on Mozilla-based browsers (where the appropriate JS command is "addEventListener()" rather than "attachEvent()"), and I've had trouble getting AttachEvent() to work reliably even in IE. So I've always just used the [ScriptableMember] attribute, and called that from JS. Is there a reason you don't want to use that? (I'd be curious to hear if anyone has any better ideas.)

Ken Smith
Updated my answer to be the right way round.
AnthonyWJones