Reputation: 4415
How can I get a a 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 () { ... }
Upvotes: 2
Views: 3540
Reputation: 7366
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.
Upvotes: 1
Reputation: 4415
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.
Upvotes: 0