Lee Quarella
Lee Quarella

Reputation: 4742

How to capture variables for async functions in a coffeescript loop?

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?

Upvotes: 3

Views: 1032

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77426

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.

Upvotes: 9

Related Questions