在 ActionScript 3 中,如何将循环中数组的当前值传递给事件侦听器

在 ActionScript 3 中,如何将循环中数组的当前值传递给事件侦听器

问题描述:

代码示例:

var gospels : Array = ["john", "mark", "matthew", "paul"];

for each (var book : String in gospels)
{
  var loader : URLLoader = new URLLoader();
  loader.load(new URLRequest("http://example.com/" + name));

  trace(book) // outputs current value of array

  loader.addEventListener(Event.COMPLETE, function(e : Event) : void {
    trace(book); // prints paul 4 times
  });
}

当事件侦听器的函数被调用时,如何让事件侦听器在循环中使用数组的值?IE.当我在事件侦听器的函数中调用 trace 时,如何让它输出 "john", "mark", "matthew",和 "paul"?

How can I get the event listener to use the value of the array in the loop when the event listener's function was called? I.e. when I call trace inside the event listener's function, how can I get it to output "john", "mark", "matthew", and "paul"?

var gospels:Array = ["john", "mark", "matthew", "paul"];

for each (var item:String in gospels)
{
  (function(book:String){
    var loader : URLLoader = new URLLoader();
    loader.load(new URLRequest("http://example.com/" + name));

    trace(book) // outputs current value of array

    loader.addEventListener(Event.COMPLETE, function(e:Event):void {
      trace(book); // prints paul 4 times
    });
  }(item));
}