开发者

Object initialization problem - not null inside function but is null when I exit function

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:

  1. function main
  2. main => load_status_system()
  3. load_status_system => dojo.xhrGet
  4. main => load_ring_topology()
  5. function main is done and exits (status_container is still null)
  6. dojo.xhrGet receives its response, calls load()
  7. load => fills status_container
  8. load alerts the new status_container and exits.
  9. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜