JavaScript objects with resetting variables -
i'm learning javascript objects , have question/problem. have following code / js object:
changed: complete code - it's appcelerator titanium project!:
spike.xhr = spike.xhr || {}; spike.xhr.init = function() { this.severresponse = ''; this.xhrmethod = 'get'; } spike.xhr.isonline = function() { if( titanium.network.online ) { return true; } else { return false; } } spike.xhr.notonline = function() { var alertdialog = titanium.ui.createalertdialog({ title: config.project_short, message: 'you not have online connect. please connect...', buttonnames: ['continue'], cancel: 0 }); alertdialog.show(); } spike.xhr.connect = function( url ) { if( spike.xhr.isonline() ) { spike.xhr.clients = ti.network.createhttpclient(); spike.xhr.clients.onload = function() { if (spike.xhr.clients.status != 200 && spike.xhr.clients.status != 201) { var alertdialog = titanium.ui.createalertdialog({ title: config.project_short, message: 'we sorry, have received status error!', buttonnames: ['continue'], cancel: 0 }); alertdialog.show(); return false; } this.serverresponse = this.responsetext; } spike.xhr.clients.onerror = function(e) { ti.api.log( 'error: ' + e.status + ': ' + e.statustext + ' - ' + e.error ); } spike.xhr.clients.open( this.xhrmethod, url ); spike.xhr.clients.send(); } else { spike.xhr.notonline(); } } spike.xhr.basicauthentication = function( username, password ) { authstr = 'basic ' +titanium.utils.base64encode( username+':'+ password); spike.xhr.client.setrequestheader( 'authorization', authstr ); } spike.xhr.setmethod = function( type ) { this.xhrmethod = type; } spike.xhr.response = function() { return this.serverresponse; } if run:
spike.xhr.connect( 'http://mydomain' ); theresponse = spike.xhr.response(); i <null> returned! - why not "this test!" or better question: have change "this test!" back?
the reason above code doesn't work because spike.xhr.connect function asynchronous. means can tell browser make request, continue doing other stuff while browser waits response come back.
javascript runs in single thread, meaning can execute 1 thing @ time. operations "ajax" calls asynchronous in browser knows how make request, doesn't block running code wait request. typically, asynchronous code called callback function, runs when request returned:
// pseudo code. spike.xhr.connect( 'http://google.com', function ( response ) { alert( 'google' ); }); alert( 'this fire before spike.xhr.connects callback' ); the callback function executed when response server comes and browser isn't doing else.
Comments
Post a Comment