سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top