Skip to content

Instantly share code, notes, and snippets.

@richsilv
Last active August 29, 2015 13:56
Show Gist options
  • Save richsilv/8833372 to your computer and use it in GitHub Desktop.
Save richsilv/8833372 to your computer and use it in GitHub Desktop.
A Meteor.js utility function to easily attach a function to a given template's "rendered" callback but only run it once, on the next render.
// Useful for occasions on which you know that an action will result in the re-rendering of a template
// (through invalidation) and you want to execute task(s) once the rendering is complete in response.
// Sometimes, you only need to execute these task(s) in response to that specific action, so it doesn't
// make sense to add the task(s) to the normal "rendered" callback and then test if they need to be executed
// every time the template is rendered.
renderOnce = function(template, oneTimeFunc, afterwards) {
// template: either a Meteor Template instance, or the string name of such an instance
// oneTimeFunc: the function you are attaching to the "rendered" callback to be run only once
// afterwards: set to true if you need the oneTimeFunc to be executed after the normal "rendered" callback,
// rather than before it
var oldRender;
if (typeof template === "string") template = Template[template];
if (!template) return false;
oldRender = template.rendered;
template.rendered = function() {
if (afterwards) {
oldRender && oldRender.apply(this, arguments);
oneTimeFunc.apply(this, arguments);
}
else {
oneTimeFunc.apply(this, arguments);
oldRender && oldRender.apply(this, arguments);
}
template.rendered = oldRender;
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment