1

I have the following For Of loop in CoffeeScript that loops through the properties of an object:

for buildingFrame of buildingNames
  $("#bt-#{buildingFrame}").click () => @displayProperties(buildingFrame)

It appears that only the last value of buildingFrame is passed to every call to @displayProperties. Searching the site I found what I think is the reason here: Possible Answer

The reason why only the last value in the loop is used is because JavaScript is a late-binding language and loops do not introduce a new scope. The solution to fix this is given in that answer in JavaScript like so:

for(var i=0; i<barValues.length; i++) function(i){
  ...
}(i);

I have tried using this solution to my coffeScript above to try and solve the problem like so:

for buildingFrame of buildingNames => (buildingFrame)
  $("#bt-#{buildingFrame}").click () => @displayProperties(buildingFrame)
(buildingFrame)

But this just gives my complier errors. Coud someone please advise me how I can tackle this problem in CS. Thanks everyone!

2 Answers 2

2

How about something like this?

for buildingFrame of buildingNames
  do (buildingFrame) =>
    $("#bt-#{buildingFrame}").click => @displayProperties(buildingFrame)

This compiles into the following JavaScript:

_fn = function(buildingFrame) {
  return $("#bt-" + buildingFrame).click(function() {
    return _this.displayProperties(buildingFrame);
  });
};

for (buildingFrame in buildingNames) {
  _fn(buildingFrame);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, I never new about Do - seams like it was written just for the very problem I was experiencing!
1

You can use the do keyword:

for buildingFrame in buildingNames
    do (buildingFrame) ->
        $("#bt-#{buildingFrame}").click () => @displayProperties(buildingFrame)

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.