javascript 如何从 Meteor 0.8.0 Blaze 中的助手访问模板实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22795887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access template instance from helpers in Meteor 0.8.0 Blaze
提问by Andrew Mao
The change in behavior for the Template.foo.rendered
callbackin 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. One way to achieve this is by using reactive helpers as in https://github.com/avital/meteor-ui-new-rendered-callback. The reactive helpers should theoretically help performance by only being triggered when relevant items change.
Meteor 0.8.0 中回调行为Template.foo.rendered
的变化意味着我们无法在模板内容发生变化时自动使用呈现的回调作为操作 DOM 的方式。实现这一点的一种方法是使用响应式助手,如https://github.com/avital/meteor-ui-new-rendered-callback。理论上,反应式助手应该仅在相关项目发生变化时触发,从而提高性能。
However, there is now a new problem: the helper no longer has access to the template instance, like the rendered
callback used to. This means that anything used to maintain state on the template instance cannot be done by helpers.
但是,现在出现了一个新问题:助手不再可以像rendered
以前的回调那样访问模板实例。这意味着任何用于维护模板实例状态的事情都不能由助手完成。
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 更新?
回答by Igor Loskutov
In the latest versions you can use more convenient Template.instance()
instead.
在最新版本中您可以使用更方便的Template.instance()
代替。
回答by Akshat
Now there's Template.instance()
which allows you to access a template's instance in helpers. e.g
现在有Template.instance()
它允许您访问助手中的模板实例。例如
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');
}
});
回答by Andrew Mao
This is currently being tracked as "one of the first things to be added" in post 0.8.0 Meteor:
这目前在 0.8.0 Meteor 后被跟踪为“首先要添加的东西之一”:
Another related issue is the ability to access data reactively in the rendered callback, which avoids this issue in the first place:
另一个相关的问题是能够在呈现的回调中被动地访问数据,这首先避免了这个问题: