流星on渲染函数后的子模板

Meteor OnRendered function after child Template

本文关键字:函数 on 流星      更新时间:2023-09-26

父模板onRendered函数先于子模板调用。如何在呈现子模板后执行父模板函数。

<template name="parent">
 {{#each object}}
  {{> child}}
 {{/each}}
</template>
<template name="child">
 <img src="someurl" data-src="someurl">
</template>

现在我需要执行一些文档准备函数所以

Template.parent.onRendered(function() { // doesnt invokes after child template
 $("img").unveil();
 $(window).trigger("lookup");
});

autorun和afterFlush的组合可能是您需要的。试一下:

Template.parent.onRendered(function() {
  this.autorun(function() {
    // replace the find with whatever is in your helper
    // which returns the children array/cursor
    if (Children.find().count()) {
      // this should run after the child templates have been rerendered
      Tracker.afterFlush(function() {
        $('img').unveil();
        $(window).trigger('lookup');
      });
    }
  });
});

虽然使用Tracker.afterFlush是一个产生所需行为的选项,但这样做的最佳方法是仅使用子模板的onRendered函数。一旦呈现子模板,所需的代码就会执行。

Template.child.onRendered(function() {
  this.$('img').unveil();
  this.$(window).trigger('lookup');
});

这种方法更自然,并且允许子模板在任何其他模板中使用,而不会"破坏"