ajsie
ajsie

Reputation: 79686

Callbacks only see last value from loop

I have this code:

for food in foods
  Person.eat ->
    console.log food

The problem here is that "food" will always be the last "food" in "foods". That is because I have the console.log in a callback function.

How can I preserve the value in the current iteration?

Upvotes: 5

Views: 867

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

You need to close over the value of a loop if you want to geneate functions to run later. This what coffee provides the do keyword for.

for food in foods
  do (food) ->
    Person.eat ->
      console.log food

See this example: https://gist.github.com/c8329fdec424de9c57ca

This occurs because your loop body has a reference to the food variable which changes values each time though the loop, and when you function if finds the closure the function was created in and finds that food variable set to the last value of the array. Using another function to in order to create a new scope solves the problem.

Upvotes: 11

Related Questions