Clean JavaScript code in your views

Comparing #2 with #3

Revision #3 was created by David Newcomb David Newcomb on Nov 27, 2014, 1:42:04 PM.

correct grammer and poor English

Content

This tutorial presents a way of separating JS code from views and passing to it values from PHP. Yii provides two handelpful ways of keeping JavaScript code close to the widgets and other elements they interact with: * strings prefixed with 'js:' * CClientScript.registerScript method Quickly, small snippets of JavaScript code turn into big ugly strings filled with PHP variables and without proper syntax highlighting.

This tutorial shows a method of organizing JavaScript code and integrating it with a PHP backend.
[...]
* 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 suchthis plugin and use them as:

~~~
[...]
# Namespaced code

By putting all your code in
suchthis 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 suchthis plugin can be registered many times. Sometimes thatis can happen when you load an action through AJAX on a page that has already registered thate script. 

This also allows extending if further, adding more functions.

Also, since there actually is a limited scope, strict mode can be enabled:
[...]