Reputation: 61138
I'm using Yii framework. On a couple of pages I want to add some custom UI stuff using jQuery. I want the result to be something like:
$(document).ready(function() {
... my code
});
I found advice to use something like this:
Yii::app()->clientScript->registerScript('testscript',"
alert('hello world');
",CClientScript::POS_READY);
However, I have a rather large javascript code (about 100 lines) and it's hard to even read it when it's inside PHP string (no syntax highlighting in editor, no code folding).
There must be some better way to do it?
I wouldn't mind even placing the code in separate .js file, but I have no clue how to load it in to document.ready handler?
Upvotes: 3
Views: 5720
Reputation: 1310
Isolate your code into a class/function in a JS file, register that with registerScriptFile, then invoke that class / method with registerScript (will then be added to the ready-method which CClientScript uses.
Upvotes: 5
Reputation: 146
Well, I've never used yii, but searching around on Google I've found that you can add javascript to yii.
I'm a .net guy, but this link may help you out. http://www.yiiframework.com/forum/index.php?/topic/4778-what-is-the-best-form-to-load-jquery/
I'm just guessing but it'll probably look like this...
Yii::app()->clientScript->registerScriptFile('/myScript.js');
And in myScript.js you'd write...
$(document).ready(function() {
alert('hi');
//js code goes here
});
Now I'm just guessing, but you'd probably have to include the jquery plugin before any of this. So, its probably something like ...
(PHP)
<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php Yii::app()->clientScript->registerScriptFile('/myScript.js'); ?>
(JQuery)
$(document).ready(function() {
alert('hi'); //script goes here
});
Upvotes: 2