Thursday, December 08, 2005 - Posts

ASP.NET 2.0 Client Callback bug

Client Callback is one of cool and a bit overlooked features of ASP.NET 2.0. A few minutes ago, when trying to prepare demo based on Client Callback I found a nice bug. When Client Callback defined following javascript code rendered to client (skeleton):
function WebForm_CallbackComplete(){
    for (i = 0; i < __pendingCallbacks[i].length; i++) {
    // Not important
    WebForm_ExecuteCallback(callbackObject);
    // Not important
    } 
}
WebForm_ExecuteCallback method invokes callback function which is defined on WebForm. The problem appears when you have global variable named i in your WebForm.  For example another "for loop": for (i = 0; i < 100; i++). In this case loop variable in WebForm_CallbackComplete receive unpredictable value and cause uexpected behavior.
Simple fix immediately solves the problem: "for (var i=0…" instead of "for (i=0..."


Conclusions:
1. Do not use global variable named i in client callback function.
2. More important: never use undeclared (global) variables in javascript, unless you are absolutely sure what are you doing.