让 Coffeescript 在 FOR 循环中创建局部变量 [英] Getting Coffeescript to create a local variable in a FOR loop

查看:22
本文介绍了让 Coffeescript 在 FOR 循环中创建局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让 dealViewItem 进入 FOR 循环的范围?目前,dealViewItem 的范围在它之外,我所有的事件侦听器都添加到最后一个 dealViewItem 中.

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)

推荐答案

这就是 do 关键字的用途.它将立即运行一个函数,并且任何与参数之一同名的局部变量都将被传递给它,从而确保正确的闭包范围.

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)

查看 这里是编译版

do 也可以在循环之外用于自执行函数.

do can also be used outside of loops for self executing functions.

#coffeescript
do ->
  foo = 'bar'

// javascript
(function() {
  var foo;
  return foo = bar;
})();

这篇关于让 Coffeescript 在 FOR 循环中创建局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆