Saturday, May 17, 2008

Correctly Wiring In a JavaScript Function

I frequently find the unstructured nature of JavaScript to be endlessly frustrating. In some cases you can use several different syntax implementations to do the same thing. Whereas in other cases you have to be deadly accurate.

Here's an example of the latter. I wrote a simple function that starts the process to clear the cache upon a page's unload. What's wrong with this syntax:

function clearCache()
{
// Detailed code here
}

window.onunload = clearCache();


It looked perfectly fine to me. But I kept getting a "Not Implemented" error. Finally, after some searching, I discovered that the last line was incorrect. What it was doing was passing the result of 'clearCache' to 'window.onunload' whereas what I wanted to do was wire-in the JavaScript function itself to this event. So the simple fix was this:

window.onunload = clearCache;

No comments:

Post a Comment