从Meteor的另一个模板获取react nativevariables

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

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

如果我在firstTmpl设置一个被动var / dict

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

你也可以在collectingTmpl ReactiveDict的父模板上设置ReactiveDict

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

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

如果你关心当前的问题(缺less数据上下文),你可以通过Template.parentData()来访问其他模板variables。

看到这个MeteorPad作为演示,按下button时,每个播放器的背景颜色将会改变。 颜色由其父模板定义:

http://meteorpad.com/pad/zoiAvwuT3XXE5ruCf/Leaderboard_Template_parentData_Bug

您也可以阅读GitHub的PullRequest关于我build议的一些更新

https://github.com/meteor/meteor/pull/4797

干杯汤姆