# jQuery() View Helper

The `jQuery()` view helper simplifies setup of your jQuery environment in your application. It takes care of loading the core and ui library dependencies if necessary and acts as a stack for all the registered onLoad javascript statements. All jQuery view helpers put their javascript code onto this stack. It acts as a collector for everything jQuery in your application with the following responsibilities:

- Handling deployment of CDN or a local path jQuery Core and UI libraries.

- Handling $(document).ready() events.

- Specifying additional stylesheet themes to use.

The `jQuery()` view helper implementation, like its `dojo()` pendant, follows the placeholder architecture implementation; the data set in it persists between view objects, and may be directly echo'd from your layout script. Since views specified in a Zend_Layout script file are rendered before the layout itself, the `jQuery()` helper can act as a stack for jQuery statements and render them into the head segment of the html page.

Contrary to Dojo, themes cannot be loaded from a CDN for the jQuery UI widgets and have to be implemented in your pages stylesheet file or loaded from an extra stylesheet file. A default theme called Flora can be obtained from the jQuery UI downloadable file.

## jQuery() View Helper Example

In this example a jQuery environment using the core and UI libraries will be needed. UI Widgets should be rendered with the Flora thema that is installed in 'public/styles/flora.all.css'. The jQuery libraries are both loaded from local paths.

To register the jQuery functionality inside the view object, you have to add the appropriate helpers to the view helper path. There are many ways of accomplishing this, based on the requirements that the jQuery helpers have. If you need them in one specific view only, you can use the addHelperPath method on initialization of this view, or right before rendering:

    $view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');

If you need them throughout your application, you can register them in your bootstrap file using access to the Controller Plugin ViewRenderer:

    $view = new Zend_View();
    $view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');

    $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
    $viewRenderer->setView($view);
    Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

Now in the view script we want to display a Date Picker and an Ajax based Link.

    <?php echo $this->ajaxLink("Show me something",
                        "/hello/world",
                        array('update' => '#content'));?>

    <div id="content"></div>

    <form method="post" action="/hello/world">
    Pick your Date: <?php echo $this->datePicker("dp1",
                                                 '',
                                                 array(
                                                    'defaultDate' =>
                                                        date('Y/m/d', time())));?>
    <input type="submit" value="Submit" />
    </form>

Both helpers now stacked some javascript statements on the jQuery helper and printed a link and a form element respectively. To access the javascript we have to utilize the jQuery() functionality. Both helpers already activated their dependencies that is they have called `jQuery()->enable()` and `jQuery()->uiEnable()`. We only have to print the jQuery() environment, and we choose to do so in the layout script's head segment:

    <html>
        <head>
            <title>A jQuery View Helper Example</title>
            <?php echo $this->jQuery(); ?>
        </head>

        <body>
            <?php echo $this->layout()->content; ?>
        </body>
    </html>

Although `$this->layout()->content;` is printed behind the `$this->jQuery()` statement, the content of the view script is rendered before. This way all the javascript onLoad code has already been put on the onLoad stack and can be printed within the head segment of the html document.

## jQuery NoConflict Mode

jQuery offers a noConflict mode that allows the library to be run side by side with other javascript libraries that operate in the global namespace, Prototype for example. The Zend Framework jQuery View Helper makes usage of the noConflict mode very easy. If you want to run Prototype and jQuery side by side you can call `ZendX_JQuery_View_Helper_JQuery::enableNoConflictMode();` and all jQuery helpers will operate in the No Conflict Mode.

### Building your own Helper with No Conflict Mode

To make use of the NoConflict Mode in your own jQuery helper, you only have to use the static method `ZendX_JQuery_View_Helper_JQuery::getJQueryHandler()` method. It returns the variable jQuery is operating in at the moment, either `$` or `$j`

    class MyHelper_SomeHelper extends Zend_View_Helper_Abstract
    {
        public function someHelper()
        {
            $jquery = $this->view->jQuery();
            $jquery->enable(); // enable jQuery Core Library

            // get current jQuery handler based on noConflict settings
            $jqHandler = ZendX_JQuery_View_Helper_JQuery::getJQueryHandler();

            $function = '("#element").click(function() '
                      . '{ alert("noConflict Mode Save Helper!"); }'
                      . ')';
            $jquery->addOnload($jqHandler . $function);
            return '';
        }
    }

## jQuery UI Themes

Since there are no online available themes to use out of the box, the implementation of the UI library themes is a bit more complex than with the Dojo helper. The jQuery UI documentation describes for each component what stylesheet information is needed and the Default and Flora Themes from the downloadable archive give hints on the usage of stylesheets. The jQuery helper offers the function `jQuery()->addStylesheet($path);` function to include the dependant stylesheets whenever the helper is enabled and rendered. You can optionally merge the required stylesheet information in your main stylesheet file.

## Methods Available

The `jQuery()` view helper always returns an instance of the jQuery placeholder container. That container object has the following methods available:

### jQuery Core Library methods

- `enable()`: explicitly enable jQuery integration.

- `disable()`: disable jQuery integration.

- `isEnabled()`: determine whether or not jQuery integration is enabled.

- `setVersion()`: set the jQuery version that is used. This also decides on the library loaded from the Google Ajax Library CDN

- `getVersion()`: get the current jQuery that is used. This also decides on the library loaded from the Google Ajax Library CDN

- `useCdn()`: Return true, if CDN usage is currently enabled

- `useLocalPath()`: Return true, if local usage is currently enabled

- `setLocalPath()`: Set the local path to the jQuery Core library

- `getLocalPath()`: If set, return the local path to the jQuery Core library

### jQuery UI Library methods

- `uiEnable()`: explicitly enable jQuery UI integration.

- `uiDisable()`: disable jQuery UI integration.

- `uiIsEnabled()`: determine whether or not jQuery UI integration is enabled.

- `setUiVersion()`: set the jQuery UI version that is used. This also decides on the library loaded from the Google Ajax Library CDN

- `getUiVersion()`: get the current jQuery UI that is used. This also decides on the library loaded from the Google Ajax Library CDN

- `useUiCdn()`: Return true, if CDN usage is currently enabled for jQuery UI

- `useUiLocal()`: Return true, if local usage is currently enabled for jQuery UI

- `setUiLocalPath()`: Set the local path to the jQuery UI library

- `getUiLocalPath()`: If set, get the local path to the jQuery UI library

### jQuery Helper Utility methods

- `setView(Zend_View_Interface $view)`: set a view instance in the container.

- `onLoadCaptureStart()`: Start capturing javascript code for jQuery onLoad execution.

- `onLoadCaptureEnd()`: Stop capturing

- `javascriptCaptureStart()`: Start capturing javascript code that has to be rendered after the inclusion of either jQuery Core or UI libraries.

- `javascriptCaptureEnd()`: Stop capturing.

- `addJavascriptFile($path)`: Add javascript file to be included after jQuery Core or UI library.

- `getJavascriptFiles()`: Return all currently registered additional javascript files.

- `clearJavascriptFiles()`: Clear the javascript files

- `addJavascript($statement)`: Add javascript statement to be included after jQuery Core or UI library.

- `getJavascript()`: Return all currently registered additional javascript statements.

- `clearJavascript()`: Clear the javascript statements.

- `addStylesheet($path)`: Add a stylesheet file that is needed for a jQuery view helper to display correctly.

- `getStylesheets()`: Get all currently registered additional stylesheets.

- `addOnLoad($statement)`: Add javascript statement that should be executed on document loading.

- `getOnLoadActions()`: Return all currently registered onLoad statements.

- `setRenderMode($mask)`: Render only a specific subset of the jQuery environment via ZendX_JQuery::RENDER_ constants. Rendering all elements is the default behaviour.

- `getRenderMode()`: Return the current jQuery environment rendering mode.

- `setCdnSsl($bool)`: Set if the CDN Google Ajax Library should be loaded from an SSL or a Non-SSL location.

These are quite a number of methods, but many of them are used for internally by all the additional view helpers and during the printing of the jQuery environment. Unless you want to build your own jQuery helper or have a complex use-case, you will probably only get in contact with a few methods of these.

## Refactoring jQuery environment with setRenderMode()

Using the current setup that was described, each page of your website would show a different subset of jQuery code that would be needed to keep the current jQuery related items running. Also different files or stylesheets may be included depending on which helpers you implemented in your application. In production stage you might want to centralize all the javascript your application generated into a single file, or disable stylesheet rendering because you have merged all the stylesheets into a single file and include it statically in your layout. To allow a smooth refactoring you can enable or disable the rendering of certain jQuery environment blocks with help of the following constants and the `jQuery()->setRenderMode($bitmask)` function.

- `ZendX_JQuery::RENDER_LIBRARY`: Renders jQuery Core and UI library

- `ZendX_JQuery::RENDER_SOURCES`: Renders additional javascript files

- `ZendX_JQuery::RENDER_STYLESHEETS`: Renders jQuery related stylesheets

- `ZendX_JQuery::RENDER_JAVASCRIPT`: Render additional javascript statements

- `ZendX_JQuery::RENDER_JQUERY_ON_LOAD`: Render jQuery onLoad statements

- `ZendX_JQuery::RENDER_ALL`: Render all previously mentioned blocks, this is default behaviour.

For an example, if you would have merged jQuery Core and UI libraries as well as other files into a single large file as well as merged stylesheets to keep HTTP requests low on your production application. You could disallow the jQuery helper to render those parts, but render all the other stuff with the following statement in your view:

    $view->jQuery()
         ->setRenderMode(ZendX_JQuery::RENDER_JAVASCRIPT |
                         ZendX_JQuery::RENDER_JQUERY_ON_LOAD);

This statement makes sure only the required javascript statements and onLoad blocks of the current page are rendered by the jQuery helper.

## Migrations

Prior to 1.8 the methods `setCdnVersion()`, `setLocalPath()` `setUiCdnVersion()` and `setUiLocalPath()` all enabled the view helper upon calling, which is considered a bug from the following perspective: If you want to use the any non-default library option, you would have to manually disable the jQuery helper aftwards if you only require it to be loaded in some scenarios. With version 1.8 the jQuery helper does only enable itsself, when `enable()` is called, which all internal jQuery View helpers do upon being called.