【问题标题】:How to access template instance from helpers in Meteor 0.8.0 Blaze如何从 Meteor 0.8.0 Blaze 中的助手访问模板实例
【发布时间】:2014-05-12 19:37:12
【问题描述】:

Meteor 0.8.0 中的change in behavior for the Template.foo.rendered callback 意味着当模板的内容发生变化时,我们无法自动使用呈现的回调来操作 DOM。实现此目的的一种方法是使用 https://github.com/avital/meteor-ui-new-rendered-callback 中的响应式助手。从理论上讲,响应式助手应该仅在相关项目发生更改时才被触发来提高性能。

但是,现在出现了一个新问题:助手不再可以访问模板实例,就像以前的 rendered 回调一样。这意味着任何用于维护模板实例状态的事情都不能由助手完成。

有没有办法同时访问模板实例的状态以及使用响应式助手来触发 Blaze 中的 DOM 更新?

【问题讨论】:

  • 您始终可以使用自定义 render 函数定义 UI.Component。例如,请参阅我对this question 的回答。
  • 谢谢,我去看看。

标签: javascript meteor


【解决方案1】:

在最新版本中,您可以改用更方便的Template.instance()

【讨论】:

    【解决方案2】:

    现在Template.instance() 允许您在帮助程序中访问模板的实例。例如

    Template.myTemplate.helpers({
        myvalue: function() {
            var tmpl = Template.instance();
    
            ...
        }
    });
    

    与 reactiveDict 一起,您可以使用它们在呈现的回调中向下传递值。

    Template.myTemplate.created = function() {
        this.templatedata = new ReactiveDict();
    
    }
    Template.myTemplate.rendered = function() {
        this.templatedata.set("myname", "value");
    };
    
    Template.myTemplate.helpers({
        myvalue: function() {
            var tmpl = Template.instance();
            return tmpl.templatedata.get('myname');
        }
    });
    

    【讨论】:

    • UI._templateInstance() 已弃用。
    【解决方案3】:

    这目前在 0.8.0 Meteor 后被跟踪为“首先要添加的东西之一”:

    https://github.com/meteor/meteor/issues/1529

    另一个相关问题是在呈现的回调中响应式访问数据的能力,这首先避免了这个问题:

    https://github.com/meteor/meteor/issues/2010

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 1970-01-01
      • 2014-05-09
      • 2016-03-07
      • 2016-06-10
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      相关资源
      最近更新 更多