模板帮助程序中出现异常:错误:Can'不要在没有DOM的组件上使用$

Exception in template helper: Error: Can't use $ on component with no DOM

本文关键字:DOM 组件 帮助程序 异常 Can 错误      更新时间:2023-09-26

我正在Meteor中做一个笔记应用程序。我有一个实时预览,当你输入时会更新,显示提交后的笔记的样子,它还渲染了标记。现在我想在预览注释中添加语法高亮显示。

如果你不完全清楚我想做什么,请在这里查看演示。试着创建一个新的音符。在预览中,我想添加语法高亮显示。

由于每次键入内容时,实时预览都需要重新运行语法高亮显示,因此我需要一种方法来挂接预览注释内容的重读器,以重新运行highlightjs代码。

对于以前版本的Meteor,只需使用Template.render = function () {...}就可以实现这一点。但这已经不可能了,因为当模板第一次渲染时,API更改为仅运行渲染一次。

我现在想尝试以下内容。在markdown渲染函数旁边添加一个模板辅助对象,这样它将在每次更新内容时运行。在这个rerender函数中,我将查找当前模板实例,并运行高亮显示代码。

模板

<template name="previewNote">
{{#if content}}
<div class="note preview">
    <h2 class="previewTitle">Preview</h2>
    <hr>
    <div class="middleNote">
        <h1>{{title}}</h1>
        <!-- THIS LINE -->
        <p class='note-content'>{{#markdown}}{{content}}{{rerender}}{{/markdown}}</p>
        <!-- THIS LINE -->
    </div>
    <hr>
    <ul class="tags bottomNote">
        {{#each tags}}
        <li class="tag"><a>{{this}}</a></li>
        {{/each}}
    </ul>
</div>
{{/if}}
</template>

JS

Template.previewNote.rerender = function () {
    // get the current template instance, and highlight all code blocks
    var codes = UI._templateInstance().findAll("pre>code");
    for (var i = 0; i < codes.length; i++) {
        hljs.highlightBlock(codes[i]);
    }
};

这看起来很扎实,直到我尝试了一下,得到了一个例外。

Exception in template helper: Error: Can't use $ on component with no DOM

我在寻找:为什么会发生这种错误,以及我如何修复它。或者另一种方法,以实现我想要的结果。

像这样使用Tracker.autorun

Template.previewNote.rendered = function(){
  this.autorun(function(){
      // every time Template.currentData is changed then this function reruns
      Template.currentData();
      var codes = self.findAll("pre>code");
      for (var i = 0; i < codes.length; i++) {
         hljs.highlightBlock(codes[i]);
      }
  })
}