Meteor:访问子模板中的反应dict变量

Meteor: Access reactive dict variable in child template

本文关键字:dict 变量 访问 Meteor      更新时间:2023-09-26

我需要在子模板中检查在父模板中创建的反应dict变量的值。

<template name="parent">
    {{ > child }}
</template>
<template name="child">
    {{#if something}}
        checked
    {{/if}}
</template>

这就是我将反应dict变量初始化为父模板的方式:

Template.parent.onCreated(function() {
    this.blabla = new ReactiveDict();
});

因此,对于父模板,这个助手正在工作:

Template.parent.helpers({
    anything: function(type) { return (Template.instance().blabla.get('foo') === 'bar') ? true : false; }
});

但这对孩子不起作用:

Template.child.helpers({
    something: function() { return (Template.instance().blabla.get('foo') === 'bar') ? true : false; }
});

那么,我如何检查子助手中变量的值呢?

这个问题的核心是关于如何找到模板的父实例。我建议阅读这里的所有答案。

我将以Sacha提出的想法为基础,举一个例子:

html

<template name="parent">
    {{ > child parentHelper=parentHelper}}
</template>
<template name="child">
  {{#if parentHelper}}
    <h1>pass</h1>
  {{else}}
    <h1>fail</h1>
  {{/if}}
</template>

js

Template.parent.onCreated(function() {
    this.dict = new ReactiveDict();
    this.dict.set('foo', 'bar');
});
Template.parent.helpers({
  parentHelper: function() {
    return Template.instance().dict.equals('foo', 'bar');
  }
});

如果这个确切的模式在你的代码中不起作用,你可以尝试上面链接问题中的其他模式。