-
Notifications
You must be signed in to change notification settings - Fork 2k
Loops don't behave like closures #3469
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The solution in Coffee is usually to use a A syntax to allow to use both |
May I ask what the usefulness of the existing implementation is? |
It's just how JS (and most languages, really. Even though some are changing it, like C#) itself behaves. If I remember correctly, Coffee used to generate IIFEs for every loop, capturing every single variable in scope, but that was removed because of the inefficiency. |
:-/ Lame, but ok. |
Feel free to leave your feedback on the answer I linked to say you'd benefit from |
While working on a project that also uses jQuery I noticed some severely unexpected behavior while using the for loop with jQuery click callbacks. After doing some investigating, I found that for loops don't behave as closures, which is something that I would expect as it is how they behave in numerous other languages.
To illustrate what I mean, take the following example. You have some markup:
and the following coffeescript:
which produces this JavaScript:
The expected behavior is that clicking the "Bacon A" button would yield an alert with "a" in it, clicking "Bacon B" would yield an alert with "b" in it, and so on. The actual result is that clicking any of the buttons yields an alert with "c" in it. You can see this behavior demonstrated in this jsfiddle example.
The solution seems to be changing the contents of the for loop to be wrapped in a self invoking function that takes in a parameter of the name you're looking for. Something like:
... and I confirmed that that appears to solve the problem.
The text was updated successfully, but these errors were encountered: