Sep
23
2008

Implementing Callback in VBScript

Callback is a function which is executed on completion of a registered event. VBScript is not a event driven language, which means we are limited in terms of events for which callback can be implemented.

This article will demonstrate how to implement a callback on finish/terminate event. This finish/terminate event could be one of the following

  • The script finishes/terminates
  • A function finishes/terminates
  • A class finishes/terminates

CallBack implementation

We will create a special CallBack class for this

Class Callback
	'The object which called
	Dim Caller
 
	'Code to be executed during callback
	Dim CallBackCode
 
	'When the class ends execute the callback code
	Sub Class_Terminate()
		Execute CallBackCode
	End Sub
End Class

Executing code when script ends
If we want a Finalize function to be called when the script ends we can use the below code

Dim OC
Set OC = New Callback
OC.CallBackCode = "Call Finalize(0)"
 
Function Finalize(ByVal ExitCode)
	Msgbox "The code end with exit code - "  & ExitCode
End Function
 
Msgbox "Script ends here"

Executing code when a function ends

Function Test()
	Dim OC
	Set OC = New CallBack
	OC.CallBackCode = "Msgbox ""Function Test ended"""
 
	x = 2/0
	Msgbox "Unreachable code"
End Function
 
Call Test()

The advantage of implementing this call back is that they are guaranteed to be executed even in case the script end with a error or the function ends with an error. In QTP we can similarly execute a code at the end of the Test by declaring the variable in one of the associate global libraries.

Note: The approach works on the concept that all variables are destroyed once the scope in which they exist ends. It is important to make sure the CallBack object is always taken in a variable declared (as shown in code “Dim OC”)

Executing the Callback on a Class method

In case we want a class method to be called on a class object we can use the caller property

Class Test
     Function CallMe()
            Msgbox "You called me"
     End Function
End Class
 
Dim oTest
Set oTest = new Test
 
Dim OC
Set OC = New CallBack
Set OC.Caller = oTest
OC.CallBackCode = "Call Caller.CallMe"
Rating: 7.2/10 (6 votes cast)
Written by Tarun Lalwani in: VBScript | Tags: , , , , , , , , , , , ,

No Comments

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.