Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Can't get callback to pass value

Hello,

I'm trying to make a small "wrapper class" for the Titanium createHTTPClient. Basically I want a way of reusing the HTTP code since I'll be using it extensivelly. Alas, maybe someone has already created a wrapper like this and can share code. I've placed comments to see if the code is even getting into the right places, and it seems like it is…simple the callback variable returns null.

Code in my app.js looks like this so far:

Ti.include('libs/http.js');

http.get('http://www.google.com',function(htmlSource){
    Ti.API.info('i am callback');
    Ti.API.info(this.responseText);
});

http.js looks like this:

var http=function(){
        return{
    get: function(value,callback){
            var xhr = Titanium.Network.createHTTPClient();

            xhr.onload = function(){
        htmlSource=this.responseText;
        Ti.API.info('i am responseText: ' + htmlSource);
        callback.call(htmlSource);
            };

            xhr.onerror = function(e){
                    Ti.API.info('Error:' + e.error);
            };

            xhr.open("GET",value,false );
        //Ti.API.info('About to enter belly of the beast');

            xhr.send();
        //Ti.API.info('Getting out of here');
    }        
        }
}();

Comments?

R. Alcocer

— asked July 4th 2010 by Ricardo Alcocer
  • http
  • javascript
  • xhr
0 Comments

2 Answers

  • Try removing the .call and just trigger the callback using callback(htmlSource); Also try using another name other than 'callback' for your callback function. That might be a javascript keyword so it might conflict.

    — answered July 4th 2010 by Sj Singh
    permalink
    0 Comments
  • Voila! That did it.

    Thank you very much Sj Singh.

    I changed the line callback.call(htmlSource) to read callback(htmlSource) and also changed the line from the previous block that read Ti.API.info(this.responseText) to Ti.API.info(htmlSource). In other words, I receive the actual value and not a reference to the internal object.

    Now it works!

    -R

    — answered July 4th 2010 by Ricardo Alcocer
    permalink
    1 Comment
    • Click on "chose as best answer" on the answer so it shows up as resolved.

      — commented July 4th 2010 by Sj Singh
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.