PDA

View Full Version : Unrecognized function syntax: class.event = (function(arg){[stuff]})(arg?);



pstephan1187
07-14-2011, 04:10 PM
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:



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:



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:



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.

DaveyErwin
07-14-2011, 04:20 PM
http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions

pstephan1187
07-14-2011, 04:33 PM
Exactly what I needed. Thank you!

DaveyErwin
07-14-2011, 08:06 PM
var a = 'A';
var b = 'B';

test = (function(t){
alert(t);
alert(b);
})(b);


alert(test)
//test(a);

Test will equal the return value
of the anonymous function, in
this case there is no reurn value
so test is undefined.