【问题标题】:MeteorJS check if template instance has a DOMMeteorJS 检查模板实例是否有 DOM
【发布时间】:2015-08-07 04:33:40
【问题描述】:

我正在尝试对辅助函数{{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。我试图检查tmpl.firstNode 是否未定义,但它不起作用。解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: javascript jquery dom meteor


    【解决方案1】:

    在模板实例被渲染时尝试设置一个属性,并检查它在你的帮助器中是否为真。

    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());
       }
    });
    

    【讨论】:

    • 谢谢,但我发现最好的方法是查看Template.instance(). view.isRendered
    【解决方案2】:

    我们可以使用tmpl.view.isRendered 属性检查模板是否被渲染(因此有一个DOM),如下所示:

    var tmpl = Template.instance();
    if(tmpl.view.isRendered){
         //Do DOM manipulation
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-21
      • 2019-09-01
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 2017-10-15
      相关资源
      最近更新 更多