传递局部变量装载机匿名处理函数 [英] Passing local variable to loader anonymous handler function

查看:130
本文介绍了传递局部变量装载机匿名处理函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不是这个工作,因为我认为这多少:

Why isn't this working as I am thinking it would:

var i:int=-1;
for each(obj in myData)
{
    i++;
    var loader:Loader=new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(event:Event)
    {
        trace(i);
    });
}

有在myData的3个对象和跟踪语句如下所示:

There are 3 objects in myData and the trace statement looks like:

2
2
2

相反的:

0
1
2

如果我加入到一个数组(如 myArr.push(我))将有3要素,0,1和2。

If I add i to an array (like myArr.push(i)) it will have 3 elements, 0, 1 and 2.

任何想法? 谢谢你。

推荐答案

首先让我来告诉你为什么,你希望不工作。 正在发生的事情是,在为通过您的元素循环,并创建所有的装载机,递增,而引发Event.COMPLETE 发生一段时间后,其中已经处于价值 2 ,所以这就是为什么你得到的输出

First let me tell you why it doesn't work as you expect. What is happening is, the for is looping through your elements, and creates all the loaders, incrementing i, but the Event.COMPLETE happens sometime later, where the i is already at the value 2, so that's why you get that output.

由于 wvxvw 建议,你需要更多的数据结构是这样的:

As wvxvw suggested, you need some more data structure, something like this:

class MyLoader {

    private var i: int;
    private var loader: Loader;

    function MyLoader(i:int) {
        this.i = i;

        loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
    }

    function onLoaded(event:Event)
    {
        trace(i);
    }
}

你会使用它在你的循环:

And you will use it in your loop:

var i:int = 0;
for each(obj in myData) {
    var loader:MyLoader=new MyLoader(i++);    
}

当然,你将需要大量添加更多的MyLoader,就像处理错误,并通过更有意义的事情,使一切工作。

Of course, you will need to add lots more to that MyLoader, like handling the errors, and pass more meaningful things to make everything work.

这篇关于传递局部变量装载机匿名处理函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆