gpt4 book ai didi

javascript - ActionScript3 中的奇怪事件监听

转载 作者:行者123 更新时间:2023-12-02 20:47:46 25 4
gpt4 key购买 nike

我在 ActionScript 中有一个奇怪的怪癖。我需要将索引传递给回调函数。

这是我的代码

for (var i:Number = 0; ((i < arrayQueue.length) && uploading); i++)
{
var lid:ListItemData=ListItemData(arrayQueue[i]);
var localI:Number= new Number(i); // to copy?
var errorCallback:Function = function():void { OnUploadError(localI); };
var progressCallback:Function = function(e:ProgressEvent):void { lid.progress = e; OnUploadProgress(localI); };
var completeCallback:Function = function():void { Alert.show('callback'+localI.toString()); OnUploadComplete(localI); }; // localI == arrayQueue.length - 1 (when called)
Alert.show(localI.toString()); // shows current i as expected
lid.fileRef.addEventListener(Event.COMPLETE, completeCallback);
lid.fileRef.addEventListener(ProgressEvent.PROGRESS, progressCallback);
lid.fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, errorCallback);
lid.fileRef.addEventListener(IOErrorEvent.IO_ERROR, errorCallback);
lid.fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorCallback);

lid.fileRef.upload(url, 'File');
}

知道如何将索引传递给我的回调吗? .upload 不会阻塞。

最佳答案

可以通过某种委托(delegate)函数或闭包为回调传递附加参数。然而,这通常被认为是一种不好的做法。您可以使用事件 target 属性来根据 FileReference 确定索引。

编辑:这是使用闭包的示例:

function getTimerClosure(ind : int) : Function {
return function(event : TimerEvent) {
trace(ind);
};
}

for (var i = 0; i < 10; i++) {
var tm : Timer = new Timer(100*i+1, 1);
tm.addEventListener(TimerEvent.TIMER, getTimerClosure(i));
tm.start();
}

这将连续跟踪从 0 到 9 的数字。

编辑2:以下是基于函数闭包创建委托(delegate)的示例:

function timerHandler(event : Event, ...rest) : void {
trace(event, rest);
}

function Delegate(scope : Object, func : Function, ...rest) : Function {
return function(...args) : void {
func.apply(scope, args.concat(rest));
}
}

var tm : Timer = new Timer(1000, 1);
tm.addEventListener(TimerEvent.TIMER, Delegate(this, this.timerHandler, 1, 2, 3));
tm.start();

然而,这是一个糟糕的方法,因为取消订阅这样的听众是一件痛苦的事情。这反过来可能会导致一些内存泄漏,从而降低应用程序的整体性能。 所以,请谨慎使用!

<小时/>

底线:如果您知道如何使用闭包,请使用它们 - 这是一件很棒的事情!如果您不关心应用程序的长远性能,请使用闭包 - 这很简单!

但是如果您不确定闭包,请使用更传统的方法。例如。根据您的情况,您可以创建一个将您的 FileReference 对象与适当索引相匹配的字典。类似这样的事情:

var frToInd : Dictionary = new Dictionary(false);
// false here wouldn't prevent garbage collection of FileReference objects

for (var i : int = 0; i < 10; i++) {
// blah-blah stuff with `lib` objects
frToInd[lib.fileRef] = i;
// another weird stuff and subscription
}

function eventListener(event : Event) : void {
// in the event listener just look up target in the dictionary
if (frToInd[event.target]) {
var ind : int = frToInd[event.target];
} else {
// Shouldn't happen since all FileReferences should be in
// the Dictionary. But if this happens - it's an error.
}
}

-- 编码愉快!

关于javascript - ActionScript3 中的奇怪事件监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/690146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com