Tuesday, May 23, 2006

Javascript bug - when an object is not an object

I ran into another Javascript bug the other day. The code read as follows:

...
MyObject.isActive.activeSlider.setValue(pos);   Eq (1)
...


This looks fine, but MyObject.isActive is one of those funny typeless Javascript beasts that mutate at the drop of a hat. In some cases it is a boolean, set like this:

...
MyObject.isActive = true;
...


In other cases it is an object with properties like activeSlider.

So what happens when MyObject.isActive is currently a boolean and Eq (1) is called? Nothing. Alarms and whistles should go off, but no - nada, bupkis.

Well, the situation was more complicated than that. Equation (1) was being evaluated from within a Javascript function that had been called by a Java applet embedded in the page. An instance of netscape.javascript.JSObject was used to call the Javascript method. And a netscape.javascript.JSException was being raised, and caught; that was visible in the Java console of my Firefox browser where the stacktrace was printed out.

But there was nothing in the Javascript console (at least, not in my version of the console). Maybe this all makes perfect sense. I haven't checked to see if an uncaught Exception in the applet appears as an error in the Javascript console (I should really do this). Maybe it's a bad idea to catch Exceptions thrown by the JSObject...

In any case, I had a hell of a time debugging this one. When I finally located the error, I added a conditional to the Javascript to verify that the property and its method exist before calling them:

...
if (MyObject.isActive &&
  MyObject.isActive.activeSlider &&
  MyObject.isActive.activeSlider.setValue) {
    MyObject.isActive.activeSlider.setValue(pos);
...
}


Oh yes, the problem is gone! And no, I did not write that Javascript...

0 Comments:

Post a Comment

<< Home