Friday, July 22, 2011

VBScript GetRef

VBScript GetRef

With GetRef function, you connect VBScript procedure/function to an HTML event.

Syntax of GetRef:

Set object.eventname = GetRef(procname)

Object: Required, It’s an object with which you associate the event.
Event: Required, It’s an event to which you bound the function.
Procedure name: Required, The name of the Sub/Function to be associated with the event.

Example 1 of GetRef

Write the below code in a notepad and save it as an HTML file. Open it via IE. This code shows the message box on load (OnLoad event) of the page.




Example 2 of GetRef

Write the below code in a notepad and save it as an HTML file. Open it via IE. This code shows the message box on clicking (OnClick event) of the button.


Example 3 of GetRef

Write the below code in a notepad and save it as a VBS file. I saved it as “a.vbs” in C: drive, went to command prompt and on the C:\ prompt wrote the filename (a) and pressed enter. This code shows the sum of the values being passed.

function Sum(byval val1, byval val2)
Sum = val1 + val2
end function

function func_1(byval funcname, byval name, byval name1)
set fp = GetRef(funcname)
msg = fp( name, name1 )
msgbox(msg)
end function

func_1 "Sum", 5, 3

Example 4 of GetRef

Write the below code in a notepad and save it as an HTML file. Open it via IE. This code shows the message box [Hello World!] on load (OnLoad event) of the page and the message box [Bye Bye!] when you close (OnUnLoad event) the page.




Example 5 of GetRef

A way to check to see if an ASP/VBScript function is defined before calling it?
Write the below code in a notepad and save it as a VBS file. I saved it as “a.vbs” in C: drive, went to command prompt and on the C:\ prompt wrote the filename (a) and pressed enter. If you run it as it is, it will show the message "test_func is defined!" and if you delete the last 3 lines i.e. delete the test_func sub, it will show the message "test_func is NOT defined"

On Error Resume Next

Dim func_ref
Set func_ref = GetRef("test_func")

If func_ref Is Nothing Then
Msgbox "test_func is NOT defined"
Else
MsgBox "test_func is defined!"
End If

Sub test_func
MsgBox "test_func!"
End Sub

Other useful links and references on GetRef:

Dezfowler
Stackoverflow -1
Stackoverflow - 2
Software Testing Forum Topic
IECON
MSDN