【问题标题】:How to execute a function after a handlebars helper has been rendered渲染把手助手后如何执行功能
【发布时间】:2013-08-13 01:46:16
【问题描述】:

如何在执行此 Handlebars 帮助程序后每次都执行一个函数?

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

这是在 Meteor 中运行的,我有一个在 Session 中设置新的“currentPage”的路由器,因为 Session 是反应式的,这会呈现我使用“currentpage”设置的模板。

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

如果是,我可以这样做:

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

Template.renderPage.rendered = function () { ... }

【问题讨论】:

  • 设置会话变量是一种解决方法。不要认为有一个后钩。

标签: javascript meteor handlebars.js


【解决方案1】:

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

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 Router 包。

【讨论】:

  • 谢谢,听起来不错!我设法用我的解决方案做到了。根模板基本上是解决方案。将函数定义为助手的一部分是不可能的,因为我想在助手渲染后操作 DOM。我正在使用路由器,但我想要一个通配符路由器/sometemplate,因为这是用于 UI 原型设计,应该很快。
  • 另见 Meteor Router 的路由功能:github.com/tmeasday/meteor-router#route-functions。它使您能够创建类似 example.com/posts/1234 的路径(其中 1234 是 ID 的通配符)。通配符处理非常灵活,可能可以处理您尝试实现的任何变化。
【解决方案2】:

所以对我有用的是使用模板而不是助手。为了让这个模板从一个陨石包中工作,我必须将它们包装在一个 Meteor.startup 函数中,否则它不会很好的模板。

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

Template.renderPage.rendered = function () { ... }

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

【讨论】:

    猜你喜欢
    • 2014-04-20
    • 2012-07-21
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2014-07-14
    相关资源
    最近更新 更多