在Meteor中从另一个模板获取响应式变量

6

我在Meteor中有一个带有一些嵌套模板的模板:

<template name="collectingTmpl">
  {{> firstTmpl}}
  {{> secondTmpl}}
</template>

如果我在firstTmpl中设置了一个响应式变量/字典
Template.firstTmpl.events({
  'click .class-name': function(event, template) {
    template.state = new ReactiveDict;
    template.state.set('someName', 'someValue');
  }
});

我可以在同一模板中使用以下代码获取这个值:

Template.firstTmpl.helpers({
  myValue: function() {
    Template.instance().state.get('someName');
  }
});

但我是否可以从secondTmpl中检索出在firstTmpl中设置的值呢?

我的意思是像这样:

Template.secondTmpl.helpers({
  myValueFromAnotherTmpl: function() {
    Template.firstTmpl.state.get('someName');
  }
});
2个回答

3
您可以选择将ReactiveDict设置在父模板上,即collectingTmpl上。
// always initialize your template instance properties
// in an onCreated lifecycle event
Template.collectingTmpl.onCreated(function(){
  this.firstTmplState = new ReactiveDict();
});

然后,您可以使用以下代码在子模板中获取对此模板实例属性的引用:

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

然后您可以在任何一个模板中使用标准的Template.instance().firstTmplState语法,它们始终指向作为collectingTmpl属性定义的同一个ReactiveVar实例。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接