Getting Coffeescript to create a local variable in a FOR loop

前端 未结 1 1811
时光取名叫无心
时光取名叫无心 2020-12-10 11:50

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 dea

相关标签:
1条回答
  • 2020-12-10 12:28

    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 讨论(0)
提交回复
热议问题