Reputation: 2634
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!
Upvotes: 1
Views: 166
Reputation: 26730
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);
}
Upvotes: 2
Reputation: 298196
You can use the do
keyword:
for buildingFrame in buildingNames
do (buildingFrame) ->
$("#bt-#{buildingFrame}").click () => @displayProperties(buildingFrame)
Upvotes: 1