View Single Post
  #1 (permalink)  
Old December 1st, 2009, 05:16 AM
ajaxbeginner ajaxbeginner is offline
Registered User
Join Date: Nov 2009
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default parameters in event handlers

In the 2nd to last page of your book you say:

"By defining these functions globally, you avoid using closures to assign event handlers. Closures are a manner in which it's possible to define a function that makes use of variables defined outside of it. They also happen to be the main cause of memory leaks in many web browsers. Whenever possible, it is preferable to create standalone functions to use as event handlers."

Does that mean that I shouldn't pass parameters to event handlers? Does that mean that I shouldn't do this:

function getInfoFromServer(numTries)
//more code not shown here
mTimer = setTimeout('getInfoFromServer(' + numTries + ')', iIntervalTryAgain);

This is for a periodic refresh. If an error occurs I want to try again. But I don't want to keep trying forever, so I pass the numTries so that I can keep track of how many tries I've made.

Is it okay to do it this way (I'm passing parameters to settimeout())? If not, how can I do this?

Here is the context in which the settimeout is called:

numTries++;"post", "[pagename]", true);
receiveReq.setRequestHeader("connection", "close");
receiveReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

receiveReq.onreadystatechange = function () {
if (receiveReq.readyState == 4) {
if (receiveReq.status == 200) {
mTimer = setTimeout('getInfoFromServer(0)', iInterval);
} else if(receiveReq.status == 12030 || receiveReq.status == 12031) {
alert('error occurred but Im continuting');
mTimer = setTimeout('getInfoFromServer(' + numTries + ')', iIntervalTryAgain);
} else {
alert("An error occurred: " + receiveReq.statusText + 'status code: ' + receiveReq.status);
mTimer = setTimeout('getInfoFromServer(' + numTries + ')', iIntervalTryAgain);

p.s. Am I handling the 12030 status code correctly?

Last edited by ajaxbeginner; December 1st, 2009 at 05:22 AM..