Hey,
just wondering what the best way to include requirejs in a yii project is?
If I have a directory of require modules in the components directory which I then want to publish with the asset manager, how could I tell require where that directory will be published to at runtime?
Also usually with require you include a data-main=“main.js” attribute in the script tag. I couldn’t see a way to do this with registerClientScript.
Does anyone have any experience or thoughts on this?
If anyone is wondering about this, here is my solution:
[list=1]
[*]Use the yii asset manager to publish a whole script directory of require modules and return a reference to the directory.
[*]Use the directory reference to registerScriptFile for require.js
[*]Include a script tag with some require config to define the base directory we got from the directory reference
[/list]
eg.
//deploy js directory of require modules and return a reference to location
$js = Yii::app()->assetManager->publish(
Yii::getPathOfAlias('application.components.js.requireModules')
);
//load require script
Yii::app()->clientScript->registerScriptFile ($js . '/require.js', CClientScript::POS_HEAD);
And then setup require js:
<script>
require.config({
baseUrl: "<?php echo $js; ?>",
waitSeconds: 15
});
require( ["module1","module2"],
function() {
//start doing things once modules have loaded
}
);
</script>
redguy
(Maciej Lizewski)
June 12, 2012, 9:42am
3
<script>
require.config({
baseUrl: "<?php echo $js; ?>",
waitSeconds: 15
});
require( ["module1","module2"],
function() {
//start doing things once modules have loaded
}
);
</script>
Rather use:
Yii::app()->clientScript->registerScript( 'requiredScript', 'require.config({
baseUrl: "' . $js . '",
waitSeconds: 15
});
require( ["module1","module2"],
function() {
//start doing things once modules have loaded
}
);', CClientScript::POS_END );
it is much more Yii-way
redguy:
Rather use:
Yii::app()->clientScript->registerScript( 'requiredScript', 'require.config({
baseUrl: "' . $js . '",
waitSeconds: 15
});
require( ["module1","module2"],
function() {
//start doing things once modules have loaded
}
);', CClientScript::POS_END );
it is much more Yii-way
Awesome, thats much nicer.
Thanks!
I have created an extension called yii-require-js for this…
I’d appreciate any feedback.
yii-require-js extension