How to implement event dispatching from a Windows Script host to a script

246 Views Asked by At

I have a C++ COM (multi-threaded apartment model) application that I build with Visual C++ 2019. I am playing with the COM-based Active Script interfaces and classes. I have a JavaScript ("JScript" really, CLSID {F414C260-6AC0-11CF-B6D1-00AA00BBBB58}) Active Script COM object created and set up. Everything works surprisingly well (for something that is falling into obscurity, unfortunately).

Is there an idiomatic approach to registering and calling event listeners where a script can use an API like like https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener and where I can dispatch events from the script host (C++)? To clarify, I am well able to call IDispatch interface methods from scripts, I want to call script functions that were passed earlier with such methods to the program, from the program. GetScriptDispatch is something else -- it lets me call methods available in the global script namespace, but I need to call functions that I pass to a proxied (from the script) "addEventListener" method.

I depend on this functionality because I want to dispatch events. Basically I want addEventListener to be available on certain proxied (e.g. objects added to script namespace with AddNamedItem) objects and I need to call event listeners added through calls to that method, when certain events in the C++ application happen.

I have read something about IConnectionPoint, and the Active Script documentation briefly mentions "event sinks" a couple of times, without there being examples on how and for what these can be used for. There is also the IBindEventHandler interface, without much explanation again as to what to use it for.

I understand this is ancient stuff, but I like COM and Active Script interface has several implementations, which to me adds utility.

1

There are 1 best solutions below

2
On

You need to create an object that implements events (see IConnectionPoint).

After starting the script you can call AddNamedItem. The script now knows the interface of you object. If it implements it can register to this events when the state changes to SCRIPTSTATE_CONNECTED.

If an event is fired, the script will receive the event and will execute the appropriate code section.

There are old samples:

  • Q168214 SAMPLE: MFCAXS (you might find it in the wayback engine)
  • And there is a sample here in code project
  • For ATL samples for Events look here