mor*_*sen 6 javascript node.js meteor
我有一个模板,在Meteor中有一些嵌套模板:
<template name="collectingTmpl">
{{> firstTmpl}}
{{> secondTmpl}}
</template>
Run Code Online (Sandbox Code Playgroud)
如果我设置的反应VAR /快译通在firstTmpl与
Template.firstTmpl.events({
'click .class-name': function(event, template) {
template.state = new ReactiveDict;
template.state.set('someName', 'someValue');
}
});
Run Code Online (Sandbox Code Playgroud)
我可以在同一模板中获取此值
Template.firstTmpl.helpers({
myValue: function() {
Template.instance().state.get('someName');
}
});
Run Code Online (Sandbox Code Playgroud)
但我还可以检索firstTmpl从中设置的值secondTmpl吗?
我的意思是
Template.secondTmpl.helpers({
myValueFromAnotherTmpl: function() {
Template.firstTmpl.state.get('someName');
}
});
Run Code Online (Sandbox Code Playgroud)
ReactiveDict您也可以在父模板上设置collectingTmpl.
// always initialize your template instance properties
// in an onCreated lifecycle event
Template.collectingTmpl.onCreated(function(){
this.firstTmplState = new ReactiveDict();
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下代码在子模板中获取对此模板实例属性的引用:
Template.firstTmpl.onCreated(function(){
// warning, this line is depending on how many parent templates
// the current template has before reaching collectingTmpl
var collectingTmplInstance = this.view.parentView.templateInstance();
this.firstTmplState = collectingTmplInstance.firstTmplState;
});
Template.secondTmpl.onCreated(function(){
var collectingTmplInstance = this.view.parentView.templateInstance();
this.firstTmplState = collectingTmplInstance.firstTmplState;
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以在 3 个模板中的任何一个中使用标准Template.instance().firstTmplState语法,并且它们将始终指向ReactiveVar定义为 的属性的同一实例collectingTmpl。