What is the best practice for passing bootstrapped variables within the rendered page (i.e. JSON data or config variables) to require.js
so they can be checked for an used by dependancies?
It looks like this could be done by checking the window
object (i.e. window.bootstrapped_models
but that does not seem very optimal.
app.html
- example data within the HTML document
<script>
var config = {
"isAdmin": true,
"userId": 1
};
var bootstrapped_models = {
"groups": [
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
}
</script>
app.js
- example app using require()
require(['jquery', 'GroupCollection'], function($, GroupCollection) {
// extend default config
if (config) {
$.extend(defaults, config);
}
// use bootstrapped JSON here
var collection = new GroupCollection;
if (bootstrapped_models.groups.length > 0) {
collection.add(bootstrapped_models.groups);
}
});
The answer from @timDunham was helpful, but it felt a little overly complicated to me. Playing around with require.js and Lithium (PHP MVC) I came up with the following. It's simple and has worked in each instance I've run into.
<script type="text/javascript">
define('bootstrapData', function () {
return <?php echo json_encode($bootstrapData) ?>;
});
</script>
Which is then available by doing the following:
define(['bootstrapData'], function(bootstrapData) {
console.log(bootstrapData); // Will output your bootstrapped object
});
Obviously the way I'm bringing the data in is language specific, but the rest should be useful regardless of your situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With