[英]MeteorJS check if template instance has a DOM
我正在嘗試對輔助函數{{htmlMarkup}}
每次評估進行一些DOM操作。 問題是當頁面加載時,在模板具有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();
}
});
我將Exception in template helper: Error: Can't use $ on template instance with no DOM
收到錯誤消息Exception in template helper: Error: Can't use $ on template instance with no DOM
。 我試圖檢查tmpl.firstNode
是否未定義,但它不起作用。 解決這個問題的最佳方法是什么?
我們可以檢查模板是否已呈現(因此具有DOM),其屬性為tmpl.view.isRendered
如下所示:
var tmpl = Template.instance();
if(tmpl.view.isRendered){
//Do DOM manipulation
}
嘗試在渲染時在模板實例上設置屬性,並檢查輔助對象中是否為真。
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();
}
});
根據您要執行的操作,您還可以在Template.onRendered
處理程序中使用Tracker.autorun
在檢測到每個輸入后執行任意代碼。
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());
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.