Using events in separated functions plus own variables
I'm trying some stuff with HTML5 Multiupload. So I have a form and can load multiple files. They are read via FileApi and fileinformation is shown to the user.
Pseudo-code:
<div id="info">
<div id="file_1">...</div>
<div id="file_2">...</div>
...
</div>
So I process all files withing $.each()
, and increment my var fileId
.
For the upload itself I add开发者_开发问答 EventListener to my XMLHTTPRequest
xhr.addEventListener("load", uploadComplete, false);
But I wan't to remove the filecontainer #file_X
when the upload is complete. So i could do this:
xhr.addEventListener("load", function(evt) {
if(evt.target.readyState == 2 && evt.target.status == 200)
{
$('#file_' + fileId).slideUp();
}
}
And my question is, can I separate this code in a function? It doesn't work that I send the event and the parameter to a separated function like this:
xhr.addEventListener("load", uploadComplete(evt, fileId), false);
Is there a smarter way then doing this:
xhr.addEventListener("load", function(evt) {
uploadComplete(evt, fileId);
});
Edit: Sorry, I misread your question. I've updated my answer.
The script doesn't work because after the $.each()
loop, var fileId
will contain the value it was given on the last iteration of the loop. So if you have 10 files, fileId
will be "file_10"
for the rest of the script (which is not what you want).
Instead of a reference to var fileId
, you want to pass your event handler the current value. Luckily, you can do just that by creating a closure:
$('#info').each(function(){
/* Do your thing, start the XHR and whatnot */
(function(currentFileId) {
xhr.addEventListener("load", function(evt) {
uploadComplete(evt, currentFileId);
});
}) (fileId);
});
You can read more about closures in any good JavaScript book or on the internet, e.g. here (MDN).
I hope this helps.
精彩评论