Meteor ReactiveVar从子模板访问父级tempate

Ram*_*san 2 javascript meteor meteor-blaze meteor-helper

我有儿童模板附带的父模板.我需要使用ReactiveVar来自子模板的父母.我可以使用Session方法,但我的要求Session方法不起作用.如何从父模板访问ReactiveVar值?

HTML:

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

<template name="ChildTemplate">
 //Some HTML content
</template>
Run Code Online (Sandbox Code Playgroud)

JS

Template.ParentTemplate.onCreated(function () {
  this.myvalue = new ReactiveVar(5); //I tried this.data.myvalue but doesnt works
});
Template.ChildTemplate.helpers({
 'myhelper' : function(){
   return Template.parentData(1).myvalue.get();
 }
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*don 5

这里有一个例子,孩子是父母的直系后裔:

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

<template name="child">
  <p>{{parentValue}}</p>
</template>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们可以像这样访问父实例变量:

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();
  }
});
Run Code Online (Sandbox Code Playgroud)

如果两个模板在DOM中具有更复杂的关系,则可以使用以下内容:

// 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();
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢.你是我的老师,回答了我的许多问题. (2认同)

mas*_*505 5

另一种可能的解决方案是明确地将数据传递给子节点.

// 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);
        },
    });
}
Run Code Online (Sandbox Code Playgroud)

并在模板文件中:

<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>
Run Code Online (Sandbox Code Playgroud)

当您按下按钮时,您将看到子模板更新.如果需要,还可以在Template.child.onCreated函数中以其他方式分配父数据.

这可能会在两个模板之间提供失败者耦合.