如何在手柄辅助对象渲染后执行函数

How to execute a function after a handlebars helper has been rendered

本文关键字:执行 函数 对象      更新时间:2023-09-26

如何在每次执行此Handlebars帮助程序后获得要执行的函数?

Handlebars.registerHelper('renderPage', function() {
    return new Handlebars.SafeString(Template[Session.get('currentPage')]());
});

这是在Meteor中运行的,我有一个路由器,它在Session中设置了一个新的"currentPage",因为Session是被动的,所以它呈现了我用"currentPage"设置的模板。

我可以使用一个带有内容元素的模板,然后使用template.templateName.rendered,但这对我不起作用,因为我希望它作为一个包,我现在认为,你不能将模板放入陨石包中。

如果是的话,我可以做:

Template.renderPage.content = function {
    return new Handlebars.SafeString(Template[Session.get('currentPage')]());
});
Template.renderPage.rendered = function () { ... }

如果希望每次运行帮助程序时都运行一个函数,为什么不将其定义为帮助程序的一部分呢?

Handlebars.registerHelper('renderPage', function() {
    var ret = new Handlebars.SafeString(Template[Session.get('currentPage')]());
    someFunctionYouWantToRun();
    return ret;
});

更广泛地说,如果您希望您的函数和助手在每次页面更改时运行,请创建一个包含其他函数和助手的根级模板,然后将其附加到该页面的.rendered():

index.html内:

<body>
  {{> root}}
</body>

root.html内:

<template name="root">
{{#if CurrentPageIsHome}}
  {{> home}}
{{/if}}
</template>

root.js:

Template.root.currentPageIsHome = function() {
  return Session.equals("currentPage", "home");
}
Template.root.rendered = function() {
  // Code you want run on every template render of root and every subtemplate
}

更好的是,使用Meteor路由器包。

所以对我来说有效的方法是使用模板而不是助手。为了让这些模板在陨石包中工作,我必须将它们封装在Meteor.startup函数中,否则它不会对模板进行微调。

Template.renderPage.content = function {
    return new Handlebars.SafeString(Template[Session.get('currentPage')]());
});
Template.renderPage.rendered = function () { ... }

然后我使用Template.xxx.rendered函数作为后挂钩。