Skip to content

Instantly share code, notes, and snippets.

@juanmendez
Created June 23, 2013 16:49
Show Gist options
  • Save juanmendez/5845671 to your computer and use it in GitHub Desktop.
Save juanmendez/5845671 to your computer and use it in GitHub Desktop.
How to configure javascript files from main page, so you can do it using a server language and apply it in your main page.
define(['module', 'ham'],function(module, ham ){
console.log( 'bread.js', module.config(), ham );
return {label:'Bread Object'};
});
define(['module'],function(module){
console.log( 'ham.js', module.config() );
return {label:'Ham Object' };
});
<!DOCTYPE html>
<html>
<head>
<title>Require JS Configuration</title>
<script src="http://requirejs.org/docs/release/2.1.6/comments/require.js"></script>
<script>
requirejs.config({
baseUrl: '',
config:{
'bread':{
kind:'<?= get_url_param('bread', 'white bread' )?>'
},
'ham':{
kind:'<?= get_url_param('ham', 'polish ham') ?>'
}
}
});
//Start the main app logic.
requirejs(['bread', 'ham' ],
function ( bread, ham ){
console.log( 'main', bread );
});
</script>
<?
//to quickly get the param values, i define here default
function get_url_param( $variable, $default='' )
{
return !empty( $_GET[ $variable ] )?$_GET[ $variable ]:$default;
}
?>
</head>
<body>
This is a small example how to provide a configuration to objects defined in dfferent Javascript files.
<a href="http://requirejs.org/" target="_blank">RequireJS</a>, makes it easy for us to pass objects to our files
within the main page. This is how i find great not to ever bother in defining php attributes inside javascript files.
Check this demo in your browser's console.
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment