views:

47

answers:

3

Basically what I'm doing is checking for the existence of an object, if it's not found, the script will try to load the source file using getScript. I only want to check this once though then return true or false to the function that calls fetch()

  fetch:function(obj){
      ...
        isReady = false;
   $.getScript(obj.srcFile,function(){

    isReady=true;
    warn("was able to load object "+key);

   });

   return isReady;

   }

but return kicks in before the script loads =/

later the script is loaded but the function returned false.

This is the beauty of asynchronous I suppose...

What's the best way to handle this... Maybe I could check again at some other point if the object exists?

Or maybe there's a better way to do this where I dont have to potentially lock the browser?

A: 

See jQuery.ajax(): Make async false.

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Skilldrick
@codeninja Have you tried this?
Skilldrick
A: 
fetch:function(obj){
 isReady = false;
 $.getScript(obj.srcFile,function(script_data){

  isReady=true;
  warn("was able to load object "+key);
  if ( typeof( script_data ) != 'undefined' ) {
     return isReady;
  }

  });


 }

You need to return the value inside the callback function, otherwise it will start the request then return straight away.

seacode
this doesnt work -- it returns undefined. Nice try. lol. I tried this too.
codeninja
Edited, try that.
seacode
sorry this is still not gonna work. getScript triggers an asynchronous call, so the parent function completes before getScript can call its success function.
codeninja
+1  A: 

From the organizing of your code I am guessing you are using an object to contain your methods. If so then you could use custom events like this:

var thing = {
    fetch: function(obj){
        var self = this;
        if (obj.isReady){
            self.trigger('ready', [obj]);
            return;
        }
        $.getScript(obj.srcFile,function(){
            obj.isReady = true;
            self.trigger('ready', [obj]);
        });
    }   
};

thing.bind('ready',function(e, obj){
    // do what you need to do when the object exists here
});
var obj = {};
thing.fetch(obj);
PetersenDidIt
I did something similar to this, rather than trying to have the trigger called in natural succession, i have it as the success handler.
codeninja