Views
Google Errors and Gotchas
From Shadowfax
The main issue I faced in developing the script was the incredibly unhelpful intermittant error condition Error Encountered. An unexpected error has occurred. With no line number on the error it took a while to track this down, but eventually the reason became very clear.
Example code often shows elements being accessd via the getElementById method. This is a useful object-oriented technique which gets hold of an object without needing to store or pass references to it. However, there is a gotcha! In order for getElementById to succeed the object must not only have been declared, but must be fully instantiated. In other words if you call getElementById too quickly after the object is declared, (for example before the page has rendered) you may get the dreaded Error Encountered. An unexpected error has occurred.
The issue in my code was I'd declared a function which was called both asynchronously (after aa button click) and synchronously (during the application start-up). The asynchronous calls needed to use getElementByID, but were never an issue because the object was always instantiated by this time. However, for the synchronous calls the object often was not always present and the error occurred.
I solved this by passing a reference to the object into the function. In the application startup code I obtained the reference from the create statement. In the button click events I obtained the reference using getElementById. Coding in this manner everything was happy.
A trivial example of this is shown below.
function doGet(e) { var app = UiApp.createApplication(); var lbl = app.createLabel("A label"); lbl.setId('myLabel'); var btnHandler = app.createServerClickHandler('doClick'); var btn = app.createButton("Toggle",btnHandler); app.add(btn); app.add(lbl); //synchronous call hilite(lbl,false); } function doClick(e) { var app = UiApp.getActiveApplication(); // asynchronous call hilite(app.getElementById('myLabel',true); } function hilite(lbl,isBold) { if (isBold) lbl.setStyleAttribute("font-weight","bold"); else lbl.setStyleAttribute("font-weight","normal"); }
Leave your comment