Sunday, 1 January 2017

closures - Javascript infamous Loop issue?

I like to write simple explanations for thick people, because I'm thick so here goes ...


We have 5 divs on the page, each with an ID ... div1, div2, div3, div4, div5


jQuery can do this ...


for (var i=1; i<=5; i++) {
$("#div" + i).click ( function() { alert ($(this).index()) } )
}

But really addressing the problem (and building this up slowly) ...


STEP 1


for (var i=1; i<=5; i++) {
$("#div" + i).click (
// TODO: Write function to handle click event
)
}

STEP 2


for (var i=1; i<=5; i++) {
$("#div" + i).click (
function(num) {
// A functions variable values are set WHEN THE FUNCTION IS CALLED!
// PLEASE UNDERSTAND THIS AND YOU ARE HOME AND DRY (took me 2 years)!
// Now the click event is expecting a function as a handler so return it
return function() { alert (num) }
}(i) // We call the function here, passing in i
)
}

SIMPLE TO UNDERSTAND ALTERNATIVE


If you can't get your head around that then this should be easier to understand and has the same effect ...


for (var i=1; i<=5; i++) {
function clickHandler(num) {
$("#div" + i).click (
function() { alert (num) }
)
}
clickHandler(i);
}

This should be simple to understand if you remember that a functions variable values are set when the function is called (but this uses the exact same thought process as before)

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...