3

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?

1 Answer 1

9

It's a classic JavaScript problem. The standard solution is to wrap each loop iteration in an anonymous function, and pass id in to that function; that way, the function you're passing to click will see that particular id instance.

CoffeeScript provides a nice syntax for this purpose: do (id) -> ... compiles to (function(id){ ... })(id). So, for your example, you'd write

for id of obj
  do (id) ->
    button = $("#my_button"+ id)
    button.click(->  console.log id)

I talk about do in my article A CoffeeScript Intervention.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.