Charlie
Charlie

Reputation: 111

COM event handler in VBScript

I want to catch the NewCivicAddressReport event which means I need to implement the event handler. Can anyone explain why the VBScript code embedded in HTML page works but the VBS file doesn't?

Here is the HTML page where NewCivicAddressReport events can be handled in the CivicFactory_NewCivicAddressReport() function. I suppose it is because of the event handler naming convention. Correct me if I'm wrong.

<body onload = "OnLoadPage()"; 
  onunload = "CivicFactory.StopListeningForReports()">

    <!-- Civic address Location report factory object -->
    <object id="CivicFactory" 
        classid="clsid:2A11F42C-3E81-4ad4-9CBE-45579D89671A"
        type="application/x-oleobject">
    </object>                 
    
    <script language="vbscript">

    Function CivicFactory_NewCivicAddressReport(report)
        MsgBox "New civic address report!"
    End Function
    
    Sub OnLoadPage()
        CivicFactory.ListenForReports(1000)
    End Sub
    
    Sub DisplayStatus(status)
        MsgBox "status displayed"
    End Sub
    
    </script>
</body>

And below is the VBS file which doesn't work - the event handler function seems never gets called.

Dim CivicFactory
Set CivicFactory = WScript.CreateObject("LocationDisp.CivicAddressReportFactory")

Function CivicFactory_NewCivicAddressReport(report)
    MsgBox "Location changed!"
    keepSleeping=false
End Function

CivicFactory.ListenForReports(1000)
    
dim keepSleeping
keepSleeping=true
while keepSleeping
    WScript.Sleep 200
wend

By the way, can anyone tell me the difference between the two ways of creating an object: <object id=...></object> and WScript.CreateObject()?

Thanks in advance!

Upvotes: 3

Views: 4961

Answers (1)

Tmdean
Tmdean

Reputation: 9299

The second argument for WScript.CreateObject is the prefix used in your event-handling Functions. For it to work, change your call to CreateObject to the following.

Set CivicFactory = _
    WScript.CreateObject("LocationDisp.CivicAddressReportFactory", _
        "CivicFactory_")

The difference between WScript.CreateObject and CreateObject is that WScript.CreateObject supports events.

Upvotes: 6

Related Questions