I was looking at the new HTML5 file API for showing a preview of an image to be uploaded. I googled for some code and almost every example had the same structure, almost the same code. I don't mind copying, particularly when it works, but I need to understand it. So I tried to understand the code but I am stuck with one area and need someone to explain that small part:
The code refers to a HTML form input field and when the file is selected shows the preview image in a img tag. Nothing fancy. Simple. Here it is after removing all the noise:
$('input[type=file]').change(function(e) {
var elem = $(this);
var file = e.target.files[0];
var reader = new FileReader();
//Part I could not understand starts here
reader.onload = (function(theFile) {
return function(e) {
var image_file = e.target.result
$('#img_id').attr('src',image_file);
};
})(file);
reader.readAsDataURL(file);
//Upto here
});
I think that reader.onload needs to be assigned a plain event handler, so I replaced the entire section marked above to:
reader.readAsDataURL(file);
reader.onload = function(e) {
var image_file = e.target.result;
//#img_id is the id of an img tag
$('#img_id').attr('src',image_file)
};
And it worked as I expected it to work.
QUESTION: What's the original code doing that the above simplified code is missing? I understand that it is a function expression returning a function and then calling it… but for what? There is just too much of the original code copied around under tutorials and what not on it but no good explanation. Please explain. Thanks