简体   繁体   中英

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

How can I get aa function to execute everytime after this Handlebars helper is executed?

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

This is running in Meteor, I have a router that sets a new 'currentPage' in Session, as Session is reactive this renders the template that I set with 'currentpage'.

I could do it by using a template with a content element, and then use Template.templateName.rendered, but this does not work for me, as I want this as a package and I by now think, that you can't put templates into meteorite packages.

If yes I could just do:

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

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

If you want a function to run every time that helper is run, why not just define it as part of the helper?

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

More broadly, if you want your function and helper to run on every page change, create a root-level template that contains the others and then attach it to that page's .rendered():

within index.html :

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

within root.html :

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

within 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
}

Better still, use the Meteor Router package.

So what's working for me, is to use a template instead of a helper. To make this templates work from a meteorite package I had to wrap them in a Meteor.startup function otherwise it wouldn't fine the Template.

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

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

And then I use Template.xxx.rendered function for an after hook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM