How to attach to COM event in Javascript

2019-09-16 03:14发布

问题:

I have followed this example to create a COM event to be used in javascript. However, I am not a fan of the final attach code?

<script for="myComComponent" event="MyFirstEvent(args)" language="javascript">
    function myComComponent::MyFirstEvent(args) {
        alert('event');
    }
</script>

What I would like is to be able to do something more like

//in the onload
myComComponent.MyFirstEvent = myJavascriptHandler;

//function setup
function myJavascript(args){
    alert('event');
}

This works in our older C++ COM event using IDispatch, however it does not work with the new C# code. Is there any way to hook the event in the onLoad? I just would like to avoid putting the javascript in the HTML...

EDIT:

I tried

myComComponent.addEventListener("MyFirstEvent", myJavascriptHandler, true); 

which should be the same as the dot notation, and this threw an exception that the event was not supported.

回答1:

We are going with this:

myComComponent.attachEvent("MyFirstEvent", myJavascriptHandler);

This works, removes the code from having to be in the HTML and is fairly clean.