Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Coffeescript to create a local variable in a FOR loop

Tags:

coffeescript

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)
like image 600
tpow Avatar asked Jul 24 '12 23:07

tpow


People also ask

How to declare a variable in CoffeeScript?

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.

Is a local variable in for loop?

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.

How do you write a CoffeeScript?

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.


1 Answers

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;
})();
like image 69
Alex Wayne Avatar answered Oct 07 '22 14:10

Alex Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!