BadClosuresFix

Fixed: Not using closures correctly or at all

by mrrodd

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
    <ul id="ulA"></ul>
    <hr/>
    <ul id="ulB"></ul>
</body>
</html>

JavaScript

// Example A
var unorderedList = $("#ulA");
for(var i = 0; i < 10; i++) {
    $("<li/>", {
        id: i,
        text: "Link " + i,
        // closure        
        click: function(index) {
            return function() {
                console.log("You've clicked " + index);
            }
        }(i)
    }).appendTo(unorderedList);
}

// Example B
var unorderedList = $("#ulB");
for(var i = 0; i < 10; i++) {
    $("<li/>", {
        id: i,
        text: "Link " + i,
        // closure        
        click: clickEventHandler(i)
    }).appendTo(unorderedList);
}

// closure
function clickEventHandler(index) {
    return function() {
        console.log("You've clicked " + index);
    }
}