You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
This tutorial presents a way of separating JS code from views and passing to it values from PHP.
- strings prefixed with 'js:'
- CClientScript.registerScript method
jQuery plugin template ¶
This defines a function that is immediately called and passed two arguments:
- a reference to window.yourPluginName
- the jQuery object
This allows you to extend the global yourPluginName object by adding methods and properties to it, keeping them all in one scope.
Now you can place your bulky JS code from your views inside this plugin and use them as:
Put that template in a .js file, for example protected/components/assets/yourPluginName.js.
Then register it in your action or view:
$path = Yii::app()->assetManager->publish(Yii::getPathOfAlias('application.components.assets')); Yii::app()->clientScript->registerScriptFile($path.'/yourPluginName.js');
Namespaced code ¶
By putting all your code in this plugin you keep them in a limited scope and thus create a namespace for it. That helps avoiding name conflicts and keeps your code cleaner.
Another important feature is that this plugin can be registered many times. Sometimes this can happen when you load an action through AJAX on a page that has already registered the script.
This also allows extending if further, adding more functions.
Also, since there actually is a limited scope, strict mode can be enabled:
This helps to detect browser-specific issues early in the development that is done using the developer's favourite browser, not the ones that clients are using.
Passing variables from PHP ¶
They can be stored inside the plugin by adding a private variable and an init() function:
Now after registering the script file add a call to the init() function on document load:
The '_settings' var is private and can be only referenced inside functions defined in yourPluginName;
Now your PHP and JS code is:
- separated and cleaner
- easier to read
- more extensible (no more hardcoded labels and urls in JS!)