开发者

In Flex, can I pass an extra parameter to callback event and have it evaluate early?

For example:

for(var i:int=0; i<someArray.length; i++)
{
    var loader:Loader=new Loader();
    loader.load(new URLRequest("开发者_开发百科http://testurl.com/test.jpg"));
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void{imageLoaded(e,i)});
}

The second paramter (i) for imageLoaded is always 1, I guess because i no longer exists and is defaulting to 1. Is it possible to get that second paramter to be evaluated when the load is started rather than on complete?


This should be doable using Flex's dynamic function construction. Check out the article I posted on how to pass additional to parameters to an event listener.


The problem is not that i already exists, but that there's only one copy of it -- by the time the callback from the first iteration runs, the value of i in your stack frame has changed. One way to work around this is to generate your function in a separate stack frame:

private function makeCallback(i:int):Function {
    return function(e:Event):void {imageLoaded(e,i);};
}

public function frob():void {
    for(var i:int=0; i<someArray.length; i++)
    {
        var loader:Loader=new Loader();
        loader.load(new URLRequest("http://testurl.com/test.jpg"));
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, makeCallback(i));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜