【问题标题】:Meteor callback when a template has been re-rendered重新渲染模板时的 Meteor 回调
【发布时间】:2014-09-22 08:50:08
【问题描述】:

我目前有一个模板,其中有一个{{#each}} 循环。我正在尝试找到一种方法来在 {{#each}} 循环完成时触发特定功能。 Template.rendered 仅在模板第一次渲染时运行,所以不幸的是它不起作用。

有什么可以做到的吗?

【问题讨论】:

  • 您是否考虑过将each 循环的内部构造为模板,然后将.rendered 函数附加到该模板上?这是人们在这里讨论过的事情,它似乎有效。

标签: meteor meteor-blaze


【解决方案1】:

我会这样做:

Template.foo.rendered=function(){
  // NEW in 0.8.3, use this.computation=Deps.autorun and
  // this.computation.stop() in destroyed callback otherwise
  this.autorun(function(){
    var cursor=Foo.find({/* same query you feed the #each with */});
    cursor.forEach(function(foo){
      // transformations on the updated model ?
      // this is important to call forEach on the cursor even if you don't do
      // anything with it because it actually triggers dependencies on documents
    });
    NEW in 0.9.1, use Deps otherwise
    Tracker.afterFlush(function(){
      // here you are guaranteed that any DOM modification implied by the
      // each loop is finished, so you can manipulate it using jQuery
      this.$(".foo-item").doStuff();
    }.bind(this));
  }.bind(this));
};

此代码设置了一个模板本地自动运行(当模板从 DOM 中删除时,计算自动停止)以使用与 #each 参数相同的查询通过游标(使用 forEach)跟踪对集合所做的更改。

只要数据库被修改,它就会再次运行,如果你愿意,你可以迭代修改过的文档。

正在修改的数据库,它还将使#each块的计算设置无效并执行DOM元素插入/修改/删除。

this.autorun创建的模板计算中,我们不确定DOM操作是否已经发生,这就是为什么我们在DOM再次冻结后使用Tracker.afterFlush来运行代码。

如果您在每次#each 失效后必须触发的代码段不使用 DOM,那么您可以忘记 Tracker.autoFlush 的东西,但我认为确实如此。

【讨论】:

  • 我在升级时遇到了一些其他问题,所以一旦我解决了这些问题,我就可以对其进行测试并标记为答案,如果它像我需要的那样工作。
  • 在模板回调中使用 this.autorun 的道具 - 毫无疑问,第一个!
  • 我现在正在努力实现这一点,但我对一件事感到困惑?在我的 HTML 中,我是否只在模板中使用 {{#each}} 而没有任何参数,并且它知道在 Template.foo.rendered 中使用 autorun
  • @saimeunt,是否有可能对此有更多的了解?
猜你喜欢
  • 2013-09-02
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 2014-03-04
  • 2014-12-08
  • 1970-01-01
相关资源
最近更新 更多