Last active
January 20, 2016 05:30
-
-
Save kevincharm/763b9522884d71a7d51f to your computer and use it in GitHub Desktop.
Accessing/passing down parent state (ReactiveDict) in Blaze
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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]; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template name="topLevel"> | |
<!-- parent template --> | |
{{> child}} | |
</template> | |
<template name="child"> | |
<!-- child template --> | |
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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