1
for a in [1,2,3]
  $('body').click (x) =>
    alert a

It alerts 3 three times when I click the body. I would like it to alert 1, 2, and 3.

1
  • I would like to click the body once and have three alerts pop up, the first with 1, second with 2, third with 3. Commented Oct 19, 2011 at 2:20

1 Answer 1

5

I screwed up the syntax the first time, but got it right this time:

You need to create a closure around the function and call it immediately (much like you would in Javascript). Coffeescript even gives you a nice syntax to do that for you... the do keyword:

for a in [1,2,3]
  do (a) ->
    $('body').click (x) =>
      alert a
Sign up to request clarification or add additional context in comments.

1 Comment

+1. See my PragPub article, A CoffeeScript Intervention, for elaboration on how this works.

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.