How can I get dealViewItem
into the scope of the FOR loop? Currently, dealViewItem is scoped outside of it, and all my event listeners are added to the last dealViewItem.
for deal in dealArray
dealViewItem = dealViewFactory.DealDetail(deal)
dealViewItem.addEventListener 'click', ->
dealCart.push(deal.dealId)
dealViewItem.setAddedToCart()
btnTakeDeals.setEnabled = true
dealHolder.add(dealViewItem)
In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.
Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name. (Emphasis mine.) Which means that the scope of the i inside your for-loop, is the for-loop. Whereas the scope of the i outside of your for-loop is the entire main method plus the for-loop.
Single-line Comments. Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag before it as shown below. Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript compiler and it compiles the rest of the code in the given file except the comments.
this is what the do
keyword is for. It will run a function immediately and any local variables with the same name as one of the arguments will be passed into it, ensuring proper closure scope.
for deal in dealArray
do (deal) ->
dealViewItem = dealViewFactory.DealDetail(deal)
dealViewItem.addEventListener 'click', ->
dealCart.push(deal.dealId)
dealViewItem.setAddedToCart()
btnTakeDeals.setEnabled = true
dealHolder.add(dealViewItem)
Check out the compiled version here
do
can also be used outside of loops for self executing functions.
#coffeescript
do ->
foo = 'bar'
// javascript
(function() {
var foo;
return foo = bar;
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With