Clean JavaScript code in your views

Comparing #3 with #4

Revision #4 was created by CeBe CeBe on Mar 25, 2018, 2:21:13 AM.

update markdown styling

Yii version

all

Tags

js,javascript, registerScript, CClientCClientScript,registerScript, js

Content

[...]
# jQuery plugin template

This template for building JavaScript plugins is proposed by jQuery:

~~~
 
[
```javascript]
(function( yourPluginName, $, undefined ) {
// public method
[...]
};
}( window.yourPluginName = window.yourPluginName || {}, jQuery ));
~~~```

This defines a function that is immediately called and passed two arguments:
[...]
Now you can place your bulky JS code from your views inside this plugin and use them as:

~~~
 
[
```javascript] yourPluginName.someCallback(); ~~~``` Put that template in a .js file, for example _protected/components/assets/yourPluginName.js_. Then register it in your action or view:
```php

$path = Yii::app()->assetManager->publish(Yii::getPathOfAlias('application.components.assets'));
Yii::app()->clientScript->registerScriptFile($path.'/yourPluginName.js');
[...]
Also, since there actually is a limited scope, strict mode can be enabled:

~~~
 
[
```javascript] (function( yourPluginName, $, undefined ) { "use strict"; // ... more code }( window.yourPluginName = window.yourPluginName || {}, jQuery )); ~~~```

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.
[...]
They can be stored inside the plugin by adding a private variable and an init() function:

~~~
 
[
```javascript]
(function( yourPluginName, $, undefined ) {
// guard to detect browser-specific issues early in development
[...]
}
}( window.yourPluginName = window.yourPluginName || {}, jQuery ));
~~~``` Now after registering the script file add a call to the init() function on document load:
```php

$options = CJavaScript::encode(array(
'someUrl' => $this->createUrl('someUrl'),
'someLabel' => Yii::t('app', 'someLabel'),
));
Yii::app()->clientScript->registerScript(__CLASS__.'#yourPluginName', "yourPluginName.init($options);", CClientScript::POS_READY);
[...]