Difference between #3 and #4 of
Clean JavaScript code in your views

Revision #4 has been created by CeBe on Mar 25, 2018, 2:21:13 AM with the memo:

update markdown styling
« previous (#3) next (#5) »

Changes

Title unchanged

Clean JavaScript code in your views

Category unchanged

Tutorials

Yii version changed

all

Tags changed

js,javascript, registerScript, CClientCClientScript,registerScript, js

Content changed

[...]
# 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);
[...]
18 0
24 followers
Viewed: 41 026 times
Version: 1.1
Category: Tutorials
Written by: nineinchnick
Last updated by: samdark
Created on: Aug 30, 2013
Last updated: 5 years ago
Update Article

Revisions

View all history