I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on:
Code:
function handleFileSelect(e){
var files = e.target.files;
var output = [];
for(var i=0,f;f=files[i];i++){
if(f.type.match('image.*')){
var reader = new FileReader();
reader.onload = (function(theFile){
return function(e){
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join('');
document.getElementById('list').insertBefore(span,null);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>';
}
document.getElementById('files').addEventListener('change',handleFileSelect,false);
To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is:
Code:
class.event = (function(arguments){
//stuff you put in a function...
})(more Arguments?);
I tried to customize a simple one to learn for myself and I wrote this:
Code:
var a = 'A';
var b = 'B';
test = (function(t){
alert(t);
alert(b);
})(b);
test(a);
The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused.
The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works.