我有 2 个单独的模板:
<template name = "MusicControl">
<!-- Some Logics here -->
</template>
<template name = "MusicSystem">
<!-- Some Logics here ("click" event) -->
</template>
Run Code Online (Sandbox Code Playgroud)
我有 2 个与这 2 个模板相关联的 JavaScript 文件。
我想要的是,如果MusicControl模板"click"上发生事件 ( event) ,它会设置某种全局变量(但不是变量),以便我可以在另一个模板中作为辅助函数访问它。 Session
如何在 Meteor 的Reactive-Dict中实现?
别担心,我在各自的 js 中为模板定义了辅助函数。
还有一件事,这些<templates>是相互独立的,我只想通过使用某种全局变量来监听<template 1>< 上的事件template 2>。
对于这种情况,我通常使用父级拥有的反应变量,其工作是在其子级之间进行协调。我不会在这里使用全局变量。
以下是基础知识。Child1 设置共享变量,Child2 使用它。父母拥有它。Child1 和 Child2 彼此没有关系。
<template name="Parent">
{{> Child1 sharedVarSetter=getSharedVarSetterFn}}
{{> Child2 sharedVar=sharedVar}}
</template>
Run Code Online (Sandbox Code Playgroud)
JS:
Template.Parent.onCreated(function() {
this.sharedVar = new ReactiveVar();
});
Template.Parent.helpers({
sharedVar() {
return Template.instance().sharedVar.get();
},
getSharedVarSetterFn() {
let template = Template.instance();
return function(newValue) {
template.sharedVar.set(newValue);
}
}
});
Template.Child1.onCreated(function() {
this.sharedVarSetterFn = new ReactiveVar(Template.currentData().sharedVarSetter);
});
Run Code Online (Sandbox Code Playgroud)
以及 Child1 中的某处(助手、事件处理程序,等等):
let fn = template.sharedVarSetterFn.get();
if (_.isFunction(fn)) {
fn(newValue);
}
Run Code Online (Sandbox Code Playgroud)
在这里,我只显示了 1 个共享变量。但如果你有多个,反应式字典也可以以同样的方式工作。