【问题标题】:Template.prototype.autorun() doesn't work inside a loopTemplate.prototype.autorun() 在循环中不起作用
【发布时间】:2015-08-27 18:44:43
【问题描述】:

我在 Template.prototype.onRendered() 中使用 Template.prototype.autorun() 来响应式更新模板。我想要多次自动运行,所以只有更新数据的部分会再次运行。这是我想象中的样子:

...
for d in [0..6]
  @autorun ->
    console.log d
    deplanements = [ 'deplanements' ]
    for h in [0..23]
      deplanements[h + 1] = 0
      Flights.find(
        eibt:
          $gte: new Date(
            weekStart.year(), weekStart.month(), weekStart.date() + d, h
          )
          $lt: new Date(
            weekStart.year(), weekStart.month(), weekStart.date() + d, h + 1
          )
      ).forEach (flight) ->
        deplanements[h + 1] += flight.passengers
      charts[d].load columns: [
        xLabels
        deplanements
        []
      ]

在第一次渲染时它工作正常,在控制台中我看到 0, 1... 6 并且模板看起来像预期的那样。但是,当我修改集合时, d 打印为 7。我不明白这是怎么可能的。如果我手动展开循环,它工作正常:

...
@autorun ->
  d = 0
  console.log d
  ...
@autorun ->
  d = 1
  console.log d
  ...
...

【问题讨论】:

    标签: meteor


    【解决方案1】:

    可能在每个自动运行中引用的d 索引是相同的,因此在for 循环之后,d 最终等于 7。这显然是一个常见的陷阱。一个简单的解决方法是call a self-invoking function within your for loop

    ...
    for d in [0..6]
      do (d) ->
        Template.instance().autorun ->
          console.log d
          deplanements = [ 'deplanements' ]
          for h in [0..23]
            deplanements[h + 1] = 0
            Flights.find(
              eibt:
                $gte: new Date(
                  weekStart.year(), weekStart.month(), weekStart.date() + d, h
                )
                $lt: new Date(
                  weekStart.year(), weekStart.month(), weekStart.date() + d, h + 1
                )
            ).forEach (flight) ->
              deplanements[h + 1] += flight.passengers
            charts[d].load columns: [
              xLabels
              deplanements
              []
            ]
    

    【讨论】:

    • 谢谢!一个补充:当在自执行函数中移动时,'this' 引用窗口而不是模板实例。所以@autorun 需要是 Template.instance().autorun.
    • 哦,确实是 :) 更正了我的回答,感谢您的反馈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多