I do a meteor call to get server data, then update a session var on the client. That session var makes a template to update itself. Now, after it is finished, I need to call a JS function (namely, PrismJS method to highlight the code shown in the template). How can that be done.
The below fires only once, on creation, and not after any change to the template.
Template.myTemplateName.onRendered(function() {
// I am doing something
});
I also tried nesting templates and updating only the inner one, trying onRendered on the outer template, but with no luck.
OK, I did a workaround by changing the div content manually with jQuery and then calling the function. It works now. I would yet love to know how to do this purely in Meteor with reactivity using a Session var.
The cleanest way IMHO to handle this is with child templates. Let’s say your method call returns an array (you can replace the ReactiveVar with a Session if you like)
Template.myTemplateName.onCreated(function(){
const instance = this;
instance.reactive = new ReactiveVar([]);
Meteor.call('something', function(err,res){
instance.reactive.set(res);
});
});
Template.myTemplateName.helpers({
reactive(){
return Template.instance().reactive.get()
}
});
Template.myTemplateNameChild.onRendered(function(){
// do your stuff
});
<template name=myTemplateName>
{{#each reactive}}
{{>myTemplateNameChild}}
{{/each}}
</template>
I think it’s cleanest to use an autorun
which depends on the same source that causes the template to update.
Template.myTemplateName.onCreated(function(){
Meteor.call('something', function(err,res){
Session.set('something', res);
});
});
Template.myTemplateName.helpers({
something(){
return Session.get('something')
}
});
Template.myTemplateName.onRendered(function(){
// We want to re-run this function
this.autorun(() => {
// Call Session.get so the autorun knows what to react to
Session.get('something');
// Wait for all template renders to finish
Tracker.afterFlush(()=> {
// Tell Prism to highlight stuff
PrismJS.highlight(this.findAll('.code'))
});
}
});