Hi,
As I'm working on a full Ajax Website (by "full Ajax" I mean that load
only once a layout and refresh only the main part), I had some
difficulties to make them dynamic and keep a design rule of "no
javascript in my views".
As most Javascript Framework works well for "inline" script tags by
evaluating them on the callback of an Ajax request, they can't evaluate
a script tag with an src attribute. So I wrote a very little helper that
keep the append/prependFile() methods. I know that such a design is not
a good idea, but for the case of you need to work on that kind of
project, I hope that will help someone saving half an hour...
I paste here the source, sorry for the message size, but it seems that
mailing list don't really like my attachment.
Lucas
<?php
class Zend_View_Helper_AjaxInlineScript extends
Zend_View_Helper_InlineScript
{
public function ajaxInlineScript($mode =
Buzzic_View_Helper_AjaxInlineScript::FILE, $spec = null, $placement =
'APPEND', array $attrs = array(), $type = 'text/javascript')
{
return $this->inlineScript($mode, $spec, $placement, $attrs,
$type);
}
/**
* Overloads the prepend/append/set File methods, for Ajax calls.
*
* @param string $method
* @param array $args
* @return Buzzic_View_Helper_HeadScript
* @throws Zend_View_Exception if too few arguments or invalid method
*/
public function __call($method, $args)
{
$matches = null;
if
(preg_match('/^(?P<action>set|(ap|pre)pend|offsetSet)(?P<mode>File|Script)$/',
$method, $matches)) {
if (1 > count($args)) {
require_once 'Zend/View/Exception.php';
throw new Zend_View_Exception(sprintf('Method "%s"
requires at least one argument', $method));
}
$action = $matches['action'];
$mode = strtolower($matches['mode']);
$type = 'text/javascript';
$attrs = array();
if ('file' != $mode) {
return parent::__call($method, $args);
}
if ('offsetSet' == $action) {
$index = array_shift($args);
if (1 > count($args)) {
require_once 'Zend/View/Exception.php';
throw new Zend_View_Exception(sprintf('Method "%s"
requires at least two arguments, an index and source', $method));
}
}
$content = $args[0];
if (isset($args[1])) {
$type = (string) $args[1];
}
if (isset($args[2])) {
$attrs = (array) $args[2];
}
if (!$this->_isDuplicate($content)) {
$filepath = str_replace('//', '/',
$_SERVER['DOCUMENT_ROOT'] . $content);
if (is_readable($filepath)) {
$item = $this->createData($type, $attrs,
file_get_contents($filepath));
if ('offsetSet' == $action) {
$this->offsetSet($index, $item);
} else {
$this->$action($item);
}
}
}
return $this;
}
return parent::__call($method, $args);
}
}