19

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)
3

1 Answer 1

38

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;
})();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.