I have code like this ( I have used Dojo for classes ):
var current_div=null;
var current_element=null;
var elements_container=null;
var status_container=null;
function main(){
//alert(status_container==null);
load_status_system();
//alert(status_container==null);
load_ring_topology();
//alert(status_container==null);
}
inside load_status_system I set function load_status_system() {
dojo.xhrGet({
url: "dynamic/status-system.json",
handleAs: "json",
load: function(obj) {开发者_JAVA百科
status_container=new STATUS_CONTAINER(obj);
alert(status_container==null);
},
error: function(err) {
alert('error during loading status-system.json');
}
});
}
Problem is that I get status_container null outside function but inside function it is not null. What is wrong with this code ? How to initialize status_container not to be null outside the function ?
Your scoping seems to be fine. I think you’re wrestling with the asynchronous nature of Ajax calls.
As posted, the order of execution of your code is as follows:
- function
main
main
=>load_status_system()
load_status_system
=>dojo.xhrGet
main
=>load_ring_topology()
- function
main
is done and exits (status_container
is stillnull
) dojo.xhrGet
receives its response, callsload()
load
=> fillsstatus_container
load
alerts the newstatus_container
and exits.- your code is done running
The solution to your problem would be to tell xhrGet
to do its call synchronously. I’ve never used Dojo, so I don’t know how to do that. Usually it’s done by setting the async
property of the XHR object to false
.
This is most likely a scoping issue. I would try accessing status_container as window.status_container
from within the XHR callback
Use dojo.hitch() to specify the scope in which the function will run.
精彩评论