You are viewing revision #1 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.
- 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 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 such 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 such 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 such plugin can be registered many times. Sometimes that happen when you load an action through AJAX on a page that already registered that 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:
Now your PHP and JS code is:
- separated and cleaner
- easier to read
- more extensible (no more hardcoded labels and urls in JS!)