Reputation: 11718
I am wondering if there is a way to pass parameters to the requireJS with the data-main parameter.
<script data-main="Main" src="lib/require/require.js"></script>
I can introduce globals:
<script>
var mainId = "Main";
var mainTarget = "body";
</script>
<script data-main="Main" src="lib/require/require.js"></script>
But I was wondering if there was a cleaner way to do it. Thanks!
EDIT:
Simon, this is a great plan I think for the mainTarget value.
require([
'plugins/load!./'+mainId+'.htm',
'plugins/load!./'+mainId+'.css'
],function(html,css){
var Main = function(){
this.__proto__ = mainTarget;
}
new Main();
}
How do I apply this to mainId?
Upvotes: 9
Views: 8219
Reputation: 8044
One way to achieve this is to create a global or common module and just use it as a dependency:
global.js
define({
foo: 'test',
bar: 'red'
});
Using the global:
require(['global'], function(global) {
console.log(global.foo) // 'test'
});
This relies on the global object properties being held within a JS file. It's also a common pattern to output data from the server side into a JS object in the HTML page. To do this you simply give your module a name.
<head>
<script>
define('global', {
mainId: 'Main',
mainTarget: 'body'
})
</script>
</head>
main.js
require(['global'], function(global) {
console.log(global.mainId) // 'Main'
});
If you define a module that needs a global property, just set the global
module as a dependency.
You can also use the priority
configuration option to ensure your global module is loaded before anything else - http://requirejs.org/docs/api.html#config
Upvotes: 15