I have 2 separate templates:
for this scenario, i generally use a reactive variable owned by the parent, whose job it is to coordinate among its children. i would not use a global variable here.
below are the basics. Child1 sets the shared var and Child2 uses it. the parent owns it. Child1 and Child2 have no relationship to one another.
<template name="Parent">
{{> Child1 sharedVarSetter=getSharedVarSetterFn}}
{{> Child2 sharedVar=sharedVar}}
</template>
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);
});
and somewhere in Child1 (helper, event handler, what have you):
let fn = template.sharedVarSetterFn.get();
if (_.isFunction(fn)) {
fn(newValue);
}
here, i've shown just 1 shared var. but if you have multiple, a reactive dict could work the same way.
A simple version of @zim's answer is:
HTML (actually Spacebars)
<template name="Parent">
{{> Child1 sharedVar1=sharedVar}}
{{> Child2 sharedVar2=sharedVar}}
</template>
JavaScript
import { ReactiveVar } from 'meteor/reactive-var';
// Just initialize the variable. Could also be within the scope of a template.
var myReactiveVar = new ReactiveVar();
Template.Parent.helpers({
// This is what will be sent to Child1 and Child2.
sharedVar: function () {
return myReactiveVar;
}
});
Template.Child1.helpers({
myValue: function () {
// As usual, this will be reactive.
return Template.instance().data.sharedVar1.get();
}
});
Template.Child2.events({
'event selector': function (event, template) {
// This change will trigger an autorun of Child1 myValue helper.
template.data.sharedVar2.set(myNewValue);
}
});
(of course you can split these into several JS files)
Example with a demo app using Meteor 1.6.1 and Blaze: https://github.com/ghybs/meteor-blaze-templates-share-data