IsDefined JavaScript Style
by Michael Dinowitz
There is a very useful function in ColdFusion called IsDefined(). This function does exactly what its name suggests; it tells if a variable is defined. I think that this would be a function in all languages, but it's not. One place that it is missing is JavaScript.
In JavaScript, if a variable does not exist, an error will be thrown. This goes beyond just variables, and includes ANY "object" used in JavaScript. For example, if I open up a sub-window for someone to select information from, the original browser window may not know if it's still open. Assuming that we used the code below when we opened the window, it is now possible to detect if the window is open or not by using a JavaScript variant of IsDefined().
|
datawindow = window.open('Javascript/pop_clientmatter.cfm?formname='+form.name+'&field=queries,
'datawindow', 'height=150,width=300,scrollbars=no,screenX=20,screenY=350');
|
This line of code will open up a new window with the following attributes:
- The window will contain the page "Javascript/pop_clientmatter.cfm".
- It will pass the url attributes "formname='+form.name+'&field=queries'".
- The new window will have a 'name' of "datawindow".
- It will be 150 pixels high and 300 pixels wide.
- It will have no scroll bar.
- The new window will have a position of 20 pixels from the left and 350 pixels from the top.
- Finally, it will be assigned to a local variable called datawindow.
This final step is the most important one. Because the new window has been assigned to a local variable, we can detect things about it. The only thing we want to know at the moment is if it's open or not. To do this we have to see if it's defined. We will use an obscure JavaScript function called typeof(). This function returns the data type of a variable. If the variable does not exist, then the data type will return as the text string "undefined".
|
if (typeof(VariableName) != "undefined")
|
This will check if the VariableName is defined or not and run some code if it is defined. Taking our open window from above, the code below will check if it exists (is open) and if it is, the code will close it.
|
if (typeof(datawindow) != "undefined")
datawindow.close();
|
There are a number of places that this can be used and you can get very creative with it. As a final note, I did not wrap the check into a function as there really is no reason. To spawn a sub-function to do a simple test like this is almost a waste. But for those who want it, here's a version as a full function:
|
function isdefined(var)
{
if(typeof(var) !="undefined")
return true;
else
return false;
}
|