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
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.
-
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