Using let in loops instead of var click handlers example
suggest changeLet’s say we need to add a button for each piece of loadedData array (for instance, each button should be a slider showing the data; for the sake of simplicity, we’ll just alert a message). One may try something like this:
for (var i = 0; i < loadedData.length; i++) {
jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
.children().last() // now let's attach a handler to the button which is a child
.on("click",function() { alert(loadedData[i].content); });
}
A click then throws TypeError, because loadedData[i] is undefined and the handler reads .content. Declare loadedData before the loop. With var, every handler shares one i. After this three-item loop, i is 3. let gives each iteration its own binding:
for (let i = 0; i < loadedData.length; i++) {
jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
.children().last() // now let's attach a handler to the button which is a child
.on("click",function() { alert(loadedData[i].content); });
}
An example of loadedData to be tested with this code:
var loadedData = [
{ label:"apple", content:"green and round" },
{ label:"blackberry", content:"small black or blue" },
{ label:"pineapple", content:"weird stuff.. difficult to explain the shape" }
];
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents