4

{{#each}}現在、ループを含むテンプレートがあります。{{#each}}そのループが終了するたびに特定の関数を起動する方法を見つけようとしています。Template.renderedテンプレートが初めてレンダリングされたときにのみ実行されるため、残念ながら機能しません。

これを行うことができるものはありますか?

4

1 に答える 1

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));
};

forEachこのコードは、 #each 引数と同じクエリを使用して、カーソル ( を使用) を介してコレクションに加えられた変更を追跡するために、テンプレートのローカル自動実行 (テンプレートが DOM から削除されると計算は自動的に停止します) をセットアップします。

データベースが変更されるたびに再実行され、必要に応じて変更されたドキュメントを反復処理できます。

データベースが変更されると、ブロックによる計算設定も無効に#eachなり、DOM 要素の挿入/変更/削除が実行されます。

によって作成されたテンプレート計算の内部ではthis.autorun、DOM 操作が既に行われたかどうかはわかりません。そのため、Tracker.afterFlushDOM が再び凍結された後にコードを実行するために a を使用します。

#each の無効化のたびに起動する必要があるコードが DOM を使用していない場合、このことは忘れてもかまいませんが、使用していると思いますTracker.autoFlush

于 2014-07-30T20:07:19.800 に答える