Last active
December 1, 2015 08:40
-
-
Save timbrandin/44632eb2c785bfe3249f to your computer and use it in GitHub Desktop.
Blaze-React (fail gracefully) context lookup using a recursive ContextProxy inspired by ES6 Proxy.
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
Test = class extends React.Component { | |
render() { | |
var context = { | |
docs: { | |
a: { | |
b: { | |
c: true | |
} | |
} | |
} | |
}; | |
// // Getting ready for ES6 Direct Proxies. | |
// if (typeof Proxy !== 'undefined') { | |
// let handler = { | |
// get: function(target, name) { | |
// if (typeof target[name] === 'object') { | |
// return new Proxy(target[name], handler); | |
// } | |
// else if (typeof target[name] !== 'undefined') { | |
// return target[name]; | |
// } | |
// else { | |
// return ''; | |
// } | |
// } | |
// }; | |
// | |
// context = new Proxy(context, handler); | |
// } | |
// XXX A temporary solution until ES6 Proxies are supported in major browsers. | |
var helper = { | |
get: function(target, name) { | |
if (typeof target[name] === 'object') { | |
return new ContextProxy(target[name], helper); | |
} | |
else if (typeof target[name] !== 'undefined') { | |
return target[name]; | |
} | |
else { | |
return ''; | |
} | |
} | |
} | |
// Recursive lookup. | |
class ContextProxy { | |
constructor(target, helper) { | |
return (dotObject) => { | |
// Do not look any further if dotObject is "". | |
if (dotObject.length == 0) { | |
return target; | |
} | |
// Split out the current name from the dotObject. | |
let [name, ...rest] = dotObject.split('.'); | |
// Look for the value for the name in the target. | |
let value = helper.get(target, name); | |
// Continue recursive to next level ContextProxy. | |
if (typeof value === 'function') { | |
return value(rest.join('.')); | |
} | |
return value; | |
}; | |
} | |
} | |
var context = new ContextProxy(context, helper); | |
return ( | |
<div> | |
{context('docs.a.b.c') ? (<span> | |
{context('docs') ? (<span> | |
Hello world | |
</span>):''} | |
</span>):''} | |
</div> | |
); | |
} | |
if (Meteor.isClient) { | |
Meteor.startup(() => { | |
let body = React.createElement(Test); | |
ReactDOM.render(body, Template._getRootNode()); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The idea is to die silent if the desired context param is not available, unlike standard React that fails totally and is unhappy about variables that are not currently used. To fully support a template system we need to fail gracefully and allow for people to first write their template and later fill in the data gaps, which gives for a much more pleasant experience.