将局部变量传递给加载器匿名处理函数
为什么这没有像我想象的那样工作:
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 个对象,跟踪语句如下所示:
2
2
2
而不是:
0
1
2
如果我将 i
添加到数组(如 myArr. Push(i)
) 它将有 3 个元素:0、1 和 2。
有什么想法吗? 谢谢。
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);
});
}
There are 3 objects in myData and the trace statement looks like:
2
2
2
Instead of:
0
1
2
If I add i
to an array (like myArr.push(i)
) it will have 3 elements, 0, 1 and 2.
Any ideas?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是你采取的一个非常糟糕的方法...只要不要做任何你想做的事情,就可以了...在这里使用匿名函数没有意义(实际上在 AS3 中从来没有) ,没有必要使用
for-each
,因为您需要的是for(;;)
。使用动态类型没有任何好处(AS3 中的动态类型没有任何好处,而且从来没有)。而且,是的,闭包将捕获上下文,上下文只有一个i
,它的值是 2,所以第一个跟踪是您应该期望的。您应该做什么 - 将加载器存储在某个数据结构中,并稍后从该数据结构中获取它们(当您需要该标识符时)。并且,为了我们用户的利益,请按顺序加载您想要加载的任何内容 - 因为如果您不这样做,我们将收到您未处理的 IO 错误...
That's a very bad approach you've taken... Just don't do any of those things you are trying to do, and it'll be fine... No point in using anonymous function here (it's never actually in AS3), no point to use
for-each
, because what you need isfor(;;)
. You use dynamic typing for no benefit what so ever (there's no benefit in dynamic typing in AS3 and never was anyway). And, yeah, the closure will capture the context, the context has only onei
, and it's value is 2, so the first trace is what you should expect.What you should be doing - store the loaders in some data structure and fetch them from that data structure later (when you need that identifier). And please, for the sake of us users, load whatever you are trying to load sequentially - because if you don't, we'll get the IO errors you aren't handling...
首先让我告诉你为什么它不能按你的预期工作。
发生的情况是, for 循环遍历您的元素,并创建所有加载器,递增
i
,但是Event.COMPLETE
稍后发生,其中i
已经是值2
,所以这就是您得到该输出的原因。正如 wvxvw 所建议的,您需要更多的数据结构,如下所示:
您将在循环中使用它:
当然,您需要向 MyLoader 添加更多内容,例如处理错误,并传递更多有意义的事情,让一切顺利进行。
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 theEvent.COMPLETE
happens sometime later, where thei
is already at the value2
, so that's why you get that output.As wvxvw suggested, you need some more data structure, something like this:
And you will use it in your loop:
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.