简体   繁体   English

如何从Meteor 0.8.0 Blaze中的助手访问模板实例

[英]How to access template instance from helpers in Meteor 0.8.0 Blaze

The change in behavior for the Template.foo.rendered callback in Meteor 0.8.0 means that we don't get to automatically use the rendered callback as a way to manipulate the DOM whenever the contents of the template change. Meteor 0.8.0中Template.foo.rendered回调的行为更改意味着,只要模板内容发生变化,我们就不会自动使用渲染回调作为操作DOM的方法。 One way to achieve this is by using reactive helpers as in https://github.com/avital/meteor-ui-new-rendered-callback . 实现此目的的一种方法是使用https://github.com/avital/meteor-ui-new-rendered-callback中的反应性助手。 The reactive helpers should theoretically help performance by only being triggered when relevant items change. 理论上,反应助手只有在相关项目发生变化时才会被触发,从而有助于提高绩效。

However, there is now a new problem: the helper no longer has access to the template instance, like the rendered callback used to. 但是,现在出现了一个新问题:帮助程序不再能够访问模板实例,就像过去使用的rendered回调一样。 This means that anything used to maintain state on the template instance cannot be done by helpers. 这意味着用于维护模板实例上的状态的任何操作都无法通过帮助程序完成。

Is there a way to access both the template instance's state as well as use reactive helpers to trigger DOM updates in Blaze? 有没有办法访问模板实例的状态以及使用反应式助手来触发Blaze中的DOM更新?

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

Now there's Template.instance() which allows you to access a template's instance in helpers. 现在有了Template.instance() ,它允许您在帮助程序中访问模板的实例。 eg 例如

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

        ...
    }
});

Along with reactiveDict, you could use them to pass values down set in the rendered callback. 与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');
    }
});

This is currently being tracked as "one of the first things to be added" in post 0.8.0 Meteor: 目前正在追踪0.8.0 Meteor中的“首先要添加的内容之一”:

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

Another related issue is the ability to access data reactively in the rendered callback, which avoids this issue in the first place: 另一个相关问题是能够在呈现的回调中被动地访问数据,这首先避免了这个问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM