Creating functions in a loop with 'closure'
by justinwyllie
HTML
<div id='container'>
</div>
JavaScript
//see http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
//see also http://rzrsharp.net/2011/06/27/what-does-coffeescripts-do-do.html
var funcs = [];
function createfunc(i) {
return function() { console.log("My value: " + i); };
}
//looping through the json returned from getJSON you build your thumbnails
//and each thumb has a click handler which when called will call openGallery() passing the clicked element
//you also build a 'global' array of callbacks which encapsulate your gallery - for that thumbnail
for (i=0; i<10; i++) {
photoGalleryJson = {'photo': i};
funcs[i] = createfunc(i);
$('#container').append($('<div id="'+i+'">added element ' + i + '</div>').
click(function() {openGallery(this)}))
}
//from the clicked element you get the id of the thumb and use this to access the correct gallery json for that thumb
function openGallery(clickedElement) {
console.log(clickedElement);
id = $(clickedElement).attr('id');
funcs[id]();
}