Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2010
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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

  • #2
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,296
    Thanks
    13
    Thanked 345 Times in 341 Posts
    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
    Last edited by Dormilich; 08-02-2010 at 07:46 PM.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • Users who have thanked Dormilich for this post:

    sjd_buffa (08-02-2010)

  • #3
    New to the CF scene
    Join Date
    Aug 2010
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Perfect! Thanks for the quick and working response.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •