PHP MVC: Where to Put Dynamically Generated Javascript -
most php mvc systems follow pattern request routed specific controller action, , controller sets bunch of variables use in view.
when you're in agency/services work environment uses lot of dynamic html ui elements, patterns leads lot of javascript being generated view variables
<script type="text/javascript"> jquery(document).ready(function(){ $('#ui-element).init( { 'param1':<?=$this->param1;?>, 'param2':<?=$this->param2;?>, } ); }); </script>
while works, i've found leads views horrible spaghetti mix of html, php , javascript. offends class of front-end developer thinks javascript should included in external files.
so, patterns/practices deal problem? specifically, when want provide default set of data javascript widget in php mvc framework, how do while keeping things clean , modular? matter of discipline, or are there specific design patterns can force modularity** here, while still giving talented client-side developers markup centric environment work in.
edit: dont have elaborate either simple have php class/function proxies ob_start/ob_get_clean , stores js somewhere outputs js elsewhere. dont have support or integrate functionality of library through php...
if somthing simple following:
class unobtrusivejshelper { protected static $_instance; protected $_js = array(); protected $_ready = array(); public static function getinstance() { } public static function setinstance(unobtrusivejshelper $instance) { } public function capturestart($key = null) { if(null !== $key) { $this->_js[$key] = null; } ob_start(); } public function captureend($key = null) { if(null !== $key) { $this->_js[$key] = ob_get_clean(); return; } $this->_js[] = ob_get_clean(); public function __tostring() { return $this->dumpjs() . $this->_dumpready(); } public function dumpjs(array $attributes = null) { if(!empty($this->_js)) { return "<script type=\"text/javascript\">". implode("\n", $this->_js) . "</script>"; } return null; } public function dumpready(array $attributes = null) { if(!empty($this->_js)) { return '<script type="text/javascript">$(document).ready(function(){'. implode("\n", $this->_js) . '});</script>'; } return null; } }
and in controller: $js = unobtrusivejshelper::getinstance();
and in view:
<?php $js->capturestart(); ?> var myjsvariable = 0; <?php $js->captureend();
and in layout (assumign two-step view here): <?php echo isset($js) ? $js : null ?>
this use helper for. example in zend_framework these little onload/ready
snippets added stack. ouput @ once in single place in head.
i have special helper use jq similar under symfony well.
these allow things $jq->setvar('myjsvar', 1);
when dump like:
var myjsvar = 1;
in script tag in head.
take @ zendx_jquery , zend_dojo , respective view helper classes example of functionality.
Comments
Post a Comment