重新渲染模板时的流星回调

Sca*_*olo 4 meteor meteor-blaze

我目前有一个模板,里面有一个{{#each}}循环.我试图找到一种方法来在该{{#each}}循环结束时触发特定的函数.Template.rendered仅在第一次呈现模板时运行,因此不幸的是不起作用.

那里有什么可以做到的吗?

sai*_*unt 5

我就是这样做的:

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));
};
Run Code Online (Sandbox Code Playgroud)

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

每当修改数据库时,它都会再次运行,如果愿意,您可以迭代修改后的文档.

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

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

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