[Project_owners] Callback functions

matthew at mjwilson.demon.co.uk matthew at mjwilson.demon.co.uk
Tue Apr 5 16:01:49 EDT 2005

sjames at uni-osnabrueck.de wrote:
> Hi all,
> I have a question about callback functions, like onreadystatechange for 
> XMLHttpRequest(). What is the best way to pass state information to 
> these functions? I find myself setting lots of global variables which 
> are then read in by the callback function, because this seems to be the 
> only way to pass information it information.  But this goes against all 
> my "good programming style" instincts. Plus, if I fire off 10 
> XMLHttpRequests at once, it seems ridiculous to need 10 separate 
> callback functions. Am I missing something obvious?

You can use OO and closures for this.

Something like (NB not tested!)

function blah () {
   this.xhr = new XMLHttpRequest();
   var _this = this;
   this.xhr.open("POST", whatever);
   this.xhr.onload = function () { _this.onload() };
   this.xhr.onerror = function () { _this.onerror(); }

blah.prototype.onload = function () {
   // ...

blah.prototype.onerror = function () {
   // ...

Any state information can be stored in instances of blah and accessed by the callback functions.


More information about the Project_owners mailing list