Pregunta

I am trying to load an image onto my stage. I use the following code:

    public function loadImg():void{

        var iLoader:Loader = new Loader();
        iLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressStatus);
        iLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderReady);

        var fileRequest:URLRequest = new URLRequest(imgPath+'testimg.JPG');
        iLoader.load(fileRequest);

    }

    public function onProgressStatus(e:ProgressEvent) {   
        trace(e.bytesLoaded, e.bytesTotal); 
    }

    public function onLoaderReady(e:Event) {     
        this.stage.addChild(iLoader); // error is here
    }

However it seems that iLoader is not found in onLoaderReady:

1120: Access of undefined property iLoader.

How do I pass object iLoader to this function? Or am I doing something wrong?

Thanks for your help in advance! :D

¿Fue útil?

Solución

See this page on Function scope. Variables defined inside a function are only available within it, so you just need to define them outside of the function:

private var iLoader:Loader;

public function loadImg():void{

    iLoader = new Loader();
    //...

}

Otros consejos

Judging from your code, it looks like iLoader is a variable scoped to the function loadImg. You can't access it by that name outside of loadImg.

One workaround is to put your declaration of iLoader in a broader scope. In this case, that would be outside of all the functions, as David Mear suggests.

However, you should be able to get around it in a more graceful way. Every event in AS3 has a target property. In this case, the target should be your loader. So inside onLoaderReady, you should be able to do the following:

 this.stage.addChild(e.target);

There's a chance this may not work - since the loader is no longer in scope, it may be deleted. I believe it will stick around long enough for this line of code to succeed, but don't have any way of testing right now. If you try it and it fails, we'll just go with David's answer and I'll delete mine.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top