views:

445

answers:

1

variable = 0;

function change() { variable = 1; }

go = newVars(); go.onLoad = function(success) { trace("#First"); change(); } go.load('http://www.stackoverflow.com/variables');

trace("#Second"); trace(variable); // output = 0;

The problem is that it executes #Second before #First, which means that the object is not fullly loaded but the code continues nonetheless. Is there a way handle this? I have tried using a while loop, but this is ugly and makes flash crash.Is there any decent way to handle this, does it have to do with better code structure/program flow or is there a technical way to make it wait? Also note: This code is executed on the server side, which means there are no frames involved.

UPDATE: When projects get bigger, this gets very ugly, especially when you are retrieving mulitple things from a server, you have to use very deep nesting, you have to keep repeating the same code, example for buying a serial:

a.onload() {

if(moneyAmount > 10){

b.onload(pay) {

sendProduct();

d.onload(serial) {

print(serial);

}

d.load('www.so.com/getSerial');

} b.load('www.so.com/pay?amount=5');

}else{

c.onload(wallet) {

displayWallet(wallet)

}

c.load('www.so.com/getWallet);

}

} a.load('www.so.com/checkMoneyAmount');

+1  A: 

It shouldn't need to wait, that's the whole reason why they expose the 'onLoad' event. Whatever code you wanted to have execute after it has fully loaded you should put inside the onLoad function.

-- edit --

That's just the nature of the beast. Javascript is not threaded, and you don't know when your web service calls will return, so you have to use an asynchronous model.

var bank = {
    onGetSerial: function(s) {
        print(serial);
    },

    onPay: function(pay) {
        sendProduct();
        d.load('www.so.com/getSerial');
    },

    onGetWallet: function(wallet) {
        displayWallet(wallet);
    },

    onCheckMoneyAmount: function(moneyAmount) {
        if (moneyAmount > 10) {
            b.load('www.so.com/pay?amount=5');
        } else {
            c.load('www.so.com/getWallet');
        }
    }
};

a.onLoad = bank.onCheckMoneyAmount;
b.onLoad = bank.onPay;
c.onLoad = bank.onGetWallet;
d.onLoad = bank.onGetSerial;

a.load('www.so.com/checkMoneyAmount');
AgileJon
I added an example in my question, what kind of solution would you suggest for that?
That way you only have to setup the onLoad handlers once, and you can focus a bit more on the logic
AgileJon