Getting Coffeescript to create a local variable in

2019-02-11 16:01发布

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)

1条回答
beautiful°
2楼-- · 2019-02-11 16:51

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;
})();
查看更多
登录 后发表回答