Working with "Out" Parameters in JavaScript
I am working with an ActiveX control in Internet Explorer 8 that is to display a save file dialog which let's the user choose a file name and file type (jpg, gif, etc). These values get passed to code and then are used in a different method to save the file. Unfortunately the method that invokes the dialog has no return value, and the file name and file type are passed in as out parameters.
The signature of the method (expressed in Visual Basic) loo开发者_JS百科ks like this:
Public Sub SaveFileDialog( _
ByVal bstrDialogType As Variant, _
ByRef pbstrFileName As String, _
ByRef out_pvType As Long _
)
The two ByRef parameters are the out parameters.
I have written the following JavaScript code:
try
{
var saveFileName, saveFileType; // out variables
gxVideoPlayBack.SaveFileDialog("image", saveFileName, saveFileType);
alert(saveFileName); // displays "undefined"
alert(saveFileType); // displays "undefined"
}
catch(error)
{
if(!error.number === -2147221484) // User clicked cancel.
{
alert(error.message);
}
}
The code works in that the ActiveX control produces its dialog, and I can handle error conditions, but I can't seem to figure out how to capture the values of the out parameters.
In the code gxVideoPlayBack is a reference to the ActiveX control embedded in the DOM via an HTML element.
If JavaScript will not work for this, can it be done in VBScript?
As an alternative I can just implement my own dialog, but would rather use the one provided.
Edit: It seems that it's not possible to have "out" parameters in JavaScript/JScript.
Original: Perhaps the approach described in this article will work:
var saveFileName={}, saveFileType={}; // Empty "output" objects.
gxVideoPlayBack.SaveFileDialog("image", saveFileName, saveFileType);
alert(saveFileName.value); // The "value" attribute is assigned ...
alert(saveFileType.value); // ... by the "SaveFileDialog" method?
I suppose the idea is that the WSH wrapper for this native call will attempt to assign the "value" property of the given output parameters, so you can either override the value setter or just give it an object with a built-in value setter.
All function arguments in JavaScript are passed by value (even if the value being passed is a reference to an object (which it is)). There is no pass-by-reference.
If SaveFileDialog
modifies the objects referenced by saveFileName
and saveFileType
then you have access to those changes through your existing variables.
Unfortunately, out/ByRef parameters will only work in JScript for objects; not for any other type (numbers, strings).
In this case, you’ll have to use VBScript, which does support ByRef arguments, or like maerics says, write a VB/VBScript wrapper for the SaveFileDialog method, which could return an object containing both file name and type.
精彩评论