MeteorJS checks if template instance has DOM
I am trying to do some DOM manipulation on every helper function evaluation {{htmlMarkup}}
. The problem is that on page load, the helper is triggered before the template has a DOM.
Template.myTemplate.helpers({
htmlMarkup:function(){
var tmpl = Template.instance();
tmpl.$('.code-container').empty();
Tracker.afterFlush(function(){
Prism.highlightElement(tmpl.$('.code-container')[0]);
});
return input.get();
}
});
I will get an error Exception in template helper: Error: Can't use $ on template instance with no DOM
. I tried to check if tmpl.firstNode
undefined is there, but it doesn't work. What is the best way to solve this problem?
We can check if a template is rendered (and therefore is a DOM) with a property tmpl.view.isRendered
like this:
var tmpl = Template.instance();
if(tmpl.view.isRendered){
//Do DOM manipulation
}
Try to set the template instance property when rendering it and check if this is true in your helper.
Template.myTemplate.onCreated(function(){
this.isRendered = false;
});
Template.myTemplate.onRendered(function(){
this.isRendered = true;
});
Template.myTemplate.helpers({
htmlMarkup:function(){
var tmpl = Template.instance();
if(!tmpl.isRendered){
return input.get();
}
tmpl.$('.code-container').empty();
//
Tracker.afterFlush(function(){
Prism.highlightElement(tmpl.$('.code-container')[0]);
});
//
return input.get();
}
});
Depending on what you are trying to do, you can also use Tracker.autorun
inside your handler Template.onRendered
to execute arbitrary code AFTER each login.
Template.myTemplate.onCreated(function(){
this.input = new ReactiveVar("");
});
Template.myTemplate.onRendered(function(){
this.autorun(function(){
var input = this.input.get();
//
this.$(".code-container").empty();
//
Tracker.afterFlush(function(){
Prism.highlightElement(this.$(".code-container")[0]);
});
});
});
Template.myTemplate.events({
"input textarea": function(event, template){
template.input.set(template.$("textarea").val());
}
});