I am looping over an object and trying to add an onclick event for each button that corresponds to each item in the object.
for id of obj
button = $("#my_button"+ id)
button.click(-> console.log id)
With this loop, every button logs the last id of the loop. How do I get each button to log the proper corresponding id?
It’s a classic JavaScript problem. The standard solution is to wrap each loop iteration in an anonymous function, and pass
idin to that function; that way, the function you’re passing toclickwill see that particularidinstance.CoffeeScript provides a nice syntax for this purpose:
do (id) -> ...compiles to(function(id){ ... })(id). So, for your example, you’d writeI talk about
doin my article A CoffeeScript Intervention.