views:

58

answers:

2

Hi, im having problems with the following code:

for (var i:Number=0; i<numFaces;i++){
    var faceLoader:Loader = new Loader();
    faceLoader.contentLoaderInfo.addEventListener( Event.INIT, 
    function(fle:Event){
        LoadCara(i,faceLoader);
        trace("LoadCara:" + i.toString());
    } );
}

function LoadCara(index:int,loader:Loader){
  if(index == 0)
  {
    trace("cara1:" + index.toString());
    cara1.removeChildAt(0);
    cara1.addChild(loader);
  }
  else if(index == 1)
  {
    cara2.removeChildAt(0);
    cara2.addChild(loader);
  }}

The problem is that im sending the variable i to the function LoadCara on every iteration, and its always called with the last value of i. I would like this function to be called with the appropiate index.

Hope I explain myself, thanks in advance.

A: 

This is not about "passing parameters by value" or not. The event handler function that you declare does not access the i variable as a parameter at all. That's why the value of i is not determined by the for loop.

There are a couple of ways to deal with this situation. You can either create a new class that extends Event, and add your index value there.

OR you can create an array and store the faceLoaders with the index that you need. And then call LoadCara() with the correct index by looking up the matching index in the array.

bitc
A: 

There is another way to achieve what you want it's not always advisable but sometimes handy...

maxmc