Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-02-2010, 10:29 AM   PM User | #1
sjd_buffa
New to the CF scene

 
Join Date: Aug 2010
Posts: 2
Thanks: 1
Thanked 0 Times in 0 Posts
sjd_buffa is an unknown quantity at this point
Accessing a callback method inside onreadystatechange handler

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
sjd_buffa is offline   Reply With Quote
Old 08-02-2010, 10:41 AM   PM User | #2
Dormilich
Senior Coder

 
Dormilich's Avatar
 
Join Date: Jan 2010
Location: Behind the Wall
Posts: 2,863
Thanks: 9
Thanked 291 Times in 287 Posts
Dormilich is on a distinguished road
Quote:
Originally Posted by sjd_buffa View Post
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:
PHP Code:
var ajax = new ...;
var 
objSelf this;
function 
handler() {
    if (
ajax.readyState==&& ajax.status==200)
        
objSelf.callback(ajax);
};
ajax.onreadystatechange handler
remember to declare all variables local, unless you must declare them global
__________________
please post your code wrapped in [CODE] [/CODE] tags

Last edited by Dormilich; 08-02-2010 at 07:46 PM..
Dormilich is offline   Reply With Quote
Users who have thanked Dormilich for this post:
sjd_buffa (08-02-2010)
Old 08-02-2010, 05:32 PM   PM User | #3
sjd_buffa
New to the CF scene

 
Join Date: Aug 2010
Posts: 2
Thanks: 1
Thanked 0 Times in 0 Posts
sjd_buffa is an unknown quantity at this point
Perfect! Thanks for the quick and working response.
sjd_buffa is offline   Reply With Quote
Reply

Bookmarks

Tags
ajax, scope

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:00 PM.


Advertisement
Log in to turn off these ads.