Javascript Meteor ReactiveVar从子模板访问父tempate

Javascript Meteor ReactiveVar从子模板访问父tempate,javascript,meteor,meteor-blaze,meteor-helper,Javascript,Meteor,Meteor Blaze,Meteor Helper,我的父模板包含在子模板中。我需要使用子模板中的parentsReactiveVar。我可以使用Session方法,但对于我的需求Session方法不起作用。如何从父模板访问ReactiveVar值 HTML: <template name="ParentTemplate"> {{> ChildTemplate}} </template> <template name="ChildTemplate"> //Some HTML content &l

我的父模板包含在子模板中。我需要使用子模板中的parents
ReactiveVar
。我可以使用
Session
方法,但对于我的需求
Session
方法不起作用。如何从父模板访问ReactiveVar值

HTML:

<template name="ParentTemplate">
   {{> ChildTemplate}}
</template>

<template name="ChildTemplate">
 //Some HTML content
</template>

下面是一个例子,如果孩子是父母的直系后裔:

<template name="parent">
  {{> child}}
</template>

<template name="child">
  <p>{{parentValue}}</p>
</template>
如果这两个模板在DOM中具有更复杂的关系,则可以使用如下内容:

Template.child.helpers({
  parentValue: function() {
    var parentView = Blaze.currentView.parentView.parentView;
    var parentInstance = parentView.templateInstance();
    // replace parentVariable with the name of the instance variable
    return parentInstance.parentVariable.get();
  }
});
// replace .parent-class will the selector for your parent template
el = $('.parent-class')[0]
var parentInstance = Blaze.getView(el).templateInstance();
// replace parentVariable with the name of the instance variable
return templateInstance.parentVariable.get();

另一种可能的解决方案是显式地将数据传递给子级

// js
if (Meteor.isClient) {
    Template.parent.onCreated(function () {
        this.reactiveV = new ReactiveVar(42);
    });

    Template.parent.helpers({
        getReactiveVar: function() {
            return Template.instance().reactiveV;
        },
    });

    Template.parent.events({
        'click button': function(e, tmp) {
            tmp.reactiveV.set(tmp.reactiveV.get() + 2);
        },
    });
}
在模板文件中:

<template name="parent">
    <p>this is the parent!</p>
    <button> var++ </button>
    {{> child parentData=getReactiveVar}}
</template>


<template name="child">
    <h3>
        child template
    </h3>
    {{parentData.get}}
</template>

这是家长

var++ {{>child parentData=getReactiveVar} 子模板 {{parentData.get}
按下按钮时,您将看到子模板更新。如果需要,还可以在
Template.child.onCreated
函数中以其他方式分配父数据


这可能会在两个模板之间提供耦合。

在父模板中,将数据放入
template.currentData()
上下文中。非常感谢。你是我的
老师
,他回答了我很多问题。
<template name="parent">
    <p>this is the parent!</p>
    <button> var++ </button>
    {{> child parentData=getReactiveVar}}
</template>


<template name="child">
    <h3>
        child template
    </h3>
    {{parentData.get}}
</template>