流星数据上下文——相对于单个模板及其后代而言是全局的
Meteor data contexts - Global with respect to a single template and its descendants
在Meteor中,想象这样一个情况:
-
Session
is too global. -
当你想让
specificVar
被模板的每个后代访问时,像{{> child specificVar=specificVar}}
那样手动传递数据给子模板太啰嗦和冗余了。
我怎么能得到中间,其中父创建一个变量,像ReactiveVar
,和任何模板生活在它(子,或他们的子,等等)可以读写这个变量?
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
, child
和grandchild
模板之间的继承关系。
这是更多的工作,但也更灵活和健壮;您指定的关系将独立于DOM结构。
相关文章:
- 全局变量和全局对象的属性之间有什么区别吗
- 正在全局范围中查找JavaScript函数
- delete关键字在全局变量上的不同行为
- 在javascript函数中设置全局变量
- 如何将getJson的响应保存在全局变量中
- 全局对象是属于哪个类的对象
- Javascript全局onclick监听器
- 从Javascript方法返回全局变量
- 访问jsrender模板中的全局javascript变量并更新它
- javascript无法重新定义函数内部的全局对象
- javascript 中的全局函数
- cordova:例外:财产'requestFileSystem'的[对象全局]不是函数
- 全局安装gull后出错
- AngularJS中的封装窗口全局变量
- 全局标志仅与第一个匹配项匹配的Regexp
- javascript隐式全局变量
- Javascript-在哪里放置常量,全局或本地
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- Javascript,从静态函数中打印全局对象
- 流星数据上下文——相对于单个模板及其后代而言是全局的