Meteor callback when a template has been re-rendered

倖福魔咒の 提交于 2019-12-20 14:43:58

问题


I currently have a template that has an {{#each}} loop within in it. I am trying to find a way to fire off a specific function whenever that {{#each}} loop has finished. Template.rendered only runs when the template has been rendered for the first time, so that doesn't work unfortunately.

Is there anything out there that can do this?


回答1:


This is how I would do it :

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

This code setup a template local autorun (computation automatically stopped when the template is removed from the DOM) to track changes made to a collection via a cursor (using forEach) using the same query as the #each argument.

Whenever the database is modified, it will run again and you can iterate over the modified documents if you will.

The database being modified, it will also invalidate the computation setup by the #each block and perform DOM elements insertion/modification/deletion.

Inside the template computation created by this.autorun, we are not sure that DOM manipulation has already taken place, that's why we use a Tracker.afterFlush to run code after DOM is frozen again.

If the piece of code you have to fire after every #each invalidation doesn't use DOM you can forget about this Tracker.autoFlush stuff, but I assume it does.



来源:https://stackoverflow.com/questions/25041451/meteor-callback-when-a-template-has-been-re-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!