...

View Full Version : Accessing a callback method inside onreadystatechange handler



sjd_buffa
08-02-2010, 10:29 AM
Hello,

This is the gist of the code:

[CODE]
function AjaxClass (url,callback) {
this.url = url;
this.callback = callback;
this.do = function () {
ajax = new ...;
ajax.onreadystatechange = function () {
if (ajax.readyState==4 && ajax.status==200)
this.callback(ajax); /* undefined */
};
ajax.open(this.url);
ajax.send();
};
}

function doSomething (ajaxObj) {
}

myAjax = new AjaxClass(doSomething);
[CODE]

[ICODE]this.callback(ajax)[ICODE] is undefined inside the onreadystatechange handler.
What am I doing wrong? Any help would be appreciated.

Thanks,
sjd_buffa

Dormilich
08-02-2010, 10:41 AM
this.callback(ajax) is undefined inside the onreadystatechange handler.
What am I doing wrong? Any help would be appreciated.

you don’t take into account, that any event handler changes the scope of the handler function to the executing object. in your case this refers to ajax, not myAjax.

you would have to use a closure to bind the this to the object you want:


var ajax = new ...;
var objSelf = this;
function handler() {
if (ajax.readyState==4 && ajax.status==200)
objSelf.callback(ajax);
};
ajax.onreadystatechange = handler;

remember to declare all variables local, unless you must declare them global

sjd_buffa
08-02-2010, 05:32 PM
Perfect! Thanks for the quick and working response.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum