I have a weird quirk in ActionScript. I need to pass the index to a callback function.
Here is my code
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'); }
Any idea on how to pass in the index to my callbacks? .upload does not block.
Passing additional parameters for your callbacks is possible via some kind of delegate function or closure. However it is often considered a bad practice. You may use event
targetproperty instead to determine your index based onFileReference.Edit: here is a sample of using closures:
This will continuously trace numbers from 0 to 9.
Edit2: here is a sample of creating a delegate based on a function closure:
However this is a bad approach since unsubscribing for such a listener is a hell pain. This in turn will probably cause some memory leakages, which will decrease overall performance of your application. So, use with caution!
Bottom line: if you know how to work with closures, use them – it is a wonderful thing! If you don’t care about your application performance in a long perspective, use closures – it’s simple!
But if you are unsure about closures, use a more conventional approach. E.g. in your case you could create a
Dictionarythat matches yourFileReferenceobjects to appropriate indices. Something like that:— Happy coding!