views:

19

answers:

2

I am creating a custom zend form element that will require some javascript. I can add the javascript I need like this:

/**
 * Renders the javascript to the view.
 */
protected function _generateJavaScript()
{
    $this->view->headScript()->captureStart(); ?>

        $(document).ready(function(){
            alert('hello');
        });

    <?php $this->view->headScript()->captureEnd();
}

However, if this custom form element is used multiple times, the identical javascript will appear multiple times. Is there a way to only render the javascript once?

A: 

You might be able to do something like

protected function _generateJavaScript()
{
    if (!isset($this->view->scriptGenerated))
    {
        // generate the script, then...
        $this->view->scriptGenerated = true;
    }
}

since PHP objects can have "extra" properties.

You'll obviously want to pick a better name, that won't clash if you have multiple scripts using the same pattern.

Alternatively, you could have the script in a file. Looks like appendFile won't include a script file more than once. I don't immediately see any such protection for ad-hoc scripts.

protected function _generateJavaScript()
{
    $this->view->headScript()->appendFile('path/to/script.js');
}
cHao
`$this->view->headScript()->appendFile()` may be the way to go. Thanks!
Andrew
A: 

Do not use capturing in this case.

HeadScript helper is smart enough to detect duplicates, but you have to use appendScript() or appendFile()

For jQuery onload functions use $this->jQuery()->addOnload('//yourcode');

takeshin