Access parent template ReactiveVar from child template?

Hopefully everyone looking for a solution makes it to the bottom. @streemo 's answer provides the most elegant way of passing local reactive variables between components

1 Like

@streemo I’m not sure if this is a good idea if you have more than one email, fullname or password component (so more than one form). As the Reactive Var is global it would change or modify all the other forms

@Lido I provided the main idea, scaling it is a different story. If you want to scale this pattern, I suggest not using ReactiveVar or ReactiveDict; instead use Collections. If you wanna see how you can do this, check out https://atmospherejs.com/streemo/meteor-react-state-tree.

I would recommend using more fleshed out solutions, but my library shows you that this fundamental pattern is definitely scalable to forms and more complex data-driven apps.

I’m just wondering why people on Blaze don’t use https://viewmodel.org/blaze to solve such issues? It’s totally easy to use (as Blaze user) and you are able to communicate with other templates.

1 Like

Who says we don’t? :wink:

1 Like

This is what I came up with. Put the shared state in a global Helpers object, not the templates. Then parent/child doesn’t matter. Helpers becomes a “state bus”.

Helpers = {
  /* general helpers for all templates */
  allSteps: [/* array of steps */],
  currentStep: new ReactiveVar('firstStep'),
} 

// Elsewhere
Template.header.helpers(Helpers);
Template.header.helpers({
  steps() {
    return Helpers.allSteps.map(step => {
      var newStep = Object.assign({}, step);  // clone the step otherwise visited steps are all active
      if (newStep.name === Helpers.currentStep.get()) newStep.active = true;
      return newStep;
    });
  },
});

@krevativ I found your variation to be best - I am using it like this:

{{> childTemplate parentHelper }}

Where parentHelper looks like this

parentHelper() {
return {
selectedItemId: Template.instance().selectedItemId
}
}

Where Template.instance().selectedItemId is a reactive var in the parent template

Now inside childTemplate I can react to changes in the parent reactive var like this:

this.selectedItemId.get()