流星数据上下文——相对于单个模板及其后代而言是全局的

Meteor data contexts - Global with respect to a single template and its descendants

本文关键字:后代 全局 上下文 数据 相对于 单个模 流星      更新时间:2023-09-26

在Meteor中,想象这样一个情况:

  • Session is too global.

  • 当你想让specificVar被模板的每个后代访问时,像{{> child specificVar=specificVar}}那样手动传递数据给子模板太啰嗦和冗余了。

我怎么能得到中间,其中父创建一个变量,像ReactiveVar,和任何模板生活在它(子,或他们的子,等等)可以读写这个变量?

例如:

Javascript

Template.parent.onCreated(function() {
  this.specificVar = new ReactiveVar([]);
});
Template.parent.helpers({
  parentHelper() {
    return Template.instance().specificVar.get();
  },
});
Template.child.helpers({
  childHelper() {
    return Template.instance().specificVar.get();
  },
});
Template.grandchild.helpers({
  grandchildHelper() {
    return Template.instance().specificVar.get();
  },
});
HTML

<template name="parent">
  {{parentHelper}}
  {{> child}}
</template>
<template name="child">
  {{childHelper}}
  {{> grandchild}}
</template>
<template name="grandchild">
  {{grandchildHelper}}
</template>

这种数据传递在vanilla Blaze中没有直接解决,但是在Blaze生态系统中有几个解决方案。

模板扩展 (https://github.com/aldeed/meteor-template-extension)

这与您在示例中想要做的非常相似。templateInstance.get(fieldName)函数允许任何后代从祖先获取所需的属性。这允许你的孙子模板写例如

Template.grandchild.helpers({
  grandchildHelper() {
    return Template.instance().get('specificVar').get();
  },
});

Blaze Components (https://github.com/peerlibrary/meteor-blaze-components)

这是一个更复杂的解决方案,包括定义parent, childgrandchild模板之间的继承关系。

这是更多的工作,但也更灵活和健壮;您指定的关系将独立于DOM结构。