开发者

Zend Framework: How to generate javascript only once?

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-&g开发者_如何学运维t;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?


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');
}


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');

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜