tscizzle
tscizzle

Reputation: 12261

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

In Meteor, Imagine a case where:

How can I get the in-between, where a parent creates a variable, like a ReactiveVar, and any template living within it (children, or their children, etc.) can read and write this variable?

For example:

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>

Upvotes: 0

Views: 25

Answers (1)

Ricky Lung
Ricky Lung

Reputation: 161

This kind of data passing isn't directly addressed within vanilla Blaze, but there are a couple workarounds within the Blaze ecosystem.

Template Extensions (https://github.com/aldeed/meteor-template-extension)

This is very similar to what you wanted to do in your example. The templateInstance.get(fieldName) function allows any descendant to fetch a desired property from the ancestor. This allows your grandchild template to write e.g.

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

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

This is a more involved solution that involves defining inheritance relationships between parent, child and grandchild templates.

This is more work but also more flexible and robust; The relationships you specify will be independent of DOM structure.

Upvotes: 1

Related Questions