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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.