views:

341

answers:

2

I have a VB.net class registered for COM interop which I'm instantiating within an HTML page using the following code:

<script type="text/javascript">
var MyClass = new ActiveXObject("Namespace.TestClass");
</script>

I can call methods on it just fine, but suppose I want to set a javascript function as a property, like so:

MyClass.TestFunction = function () { alert("It worked!"); }

How would I set my vb.net code up to be able to fire that function? This is how MSXML works in javascript for XMLHttpRequest objects, you can set

XHR.onreadystatechange = function () {}

I'm looking for a similar implementation in my class.

A: 

You have to expose a COM event, and assign the JavaScript method to that event. This way, when you invoke the event in your code, the JavaScript method will be called.

Example -

C# Code

[ComVisible(false)]
public delegate void OperationCompleted(string message); //No need to expose this delegate

public event OperationCompleted OnOperationCompleted;

if(OnOperationCompleted != null)
    OnOperationCompleted("Hello World!");

JavaScript

comObject.OnOperationCompleted = function(message) { alert(message); }

Note: I have done this before. And I guess there was some COM related error. To resolve it I had to attach some attribute somewhere in the code (I don't remember it exactly right now). But you'll be able to figure it out or google it.

Kirtan
Thanks for the suggestion. I had a few problems getting some events to fire using this method, while others would fire fine one of my events wouldn't fire at all, even though they were declared in the same way. That's pretty much the whole reason I was trying it this way anyway.
Andy E
A: 

After trying for a while, we managed to figure out a solution that worked pretty well. Since we're setting a javascript function to the property, all the properties and methods on that function are made available to the VB.net, including the javascript standard methods, call and apply:

(function () { alert("Hello"); }).call();

The solution was to just invoke the call method in the VB.net code and it seems to work pretty well.

Andy E
Hi Andy. I'm currently having the same issue as you were, and was hoping you could elaborate a bit for me. In your example, what type is the TestFunction property in the vb.net code? Is it an object, or a delegate, or what? And how exactly are you invoking the "call" method in the vb.net code?
Paul Nearney
@Paul Nearney: My .net dev is away at the moment and I haven't spoken to him directly, but I'm fairly sure the type was Object. I'm not as sure about this, but I think invoking the method was the same as/similar to JavaScript - `TestFunction.call()`
Andy E