Skip to content

Instantly share code, notes, and snippets.

@kevincharm
Last active January 20, 2016 05:30
Show Gist options
  • Save kevincharm/763b9522884d71a7d51f to your computer and use it in GitHub Desktop.
Save kevincharm/763b9522884d71a7d51f to your computer and use it in GitHub Desktop.
Accessing/passing down parent state (ReactiveDict) in Blaze
/**
* Global helper for applying parent state to current template.
* Usage:
* Invoke superstate(this); in a Template.onCreated callback to inherit parent state.
* @param templateInstance {Object} The current Blaze.View object to pass in.
* @returns {Object} The state object.
*/
superstate = (templateInstance, stateProp) => {
// defaults to Template.instance().state
if (!stateProp) stateProp = 'state';
// traverse up until Blaze.View is a {{> template}} and not a condition block
let parent = templateInstance.view.parentView;
while (parent && !parent.hasOwnProperty('template')) {
parent = parent.parentView &&
parent.parentView._templateInstance &&
parent.parentView._templateInstance[stateProp] ?
parent.parentView : null;
}
// return null if parent doesn't exist
if (!parent) return null;
return templateInstance.state = parent._templateInstance[stateProp];
};
<template name="topLevel">
<!-- parent template -->
{{> child}}
</template>
<template name="child">
<!-- child template -->
</template>
Template.topLevel.onCreated(function () {
this.state = new ReactiveDict();
this.state.set('foo', 'bar');
});
Template.child.onCreated(function () {
superstate(this);
console.log(this.state.get('foo')); // bar
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment