I have a php application that makes use of a Listener class, which basically just sets up an ajax request with jquery (example below). But for some reason, echoing the javascript just seems inelegant. Is it better practice to build a singleton class for the javascript to be passed to (which could introduce coupling) or to just echo the script like I’m doing now?
Here’s a code snippet of what I’m doing.
<?php
$script = "
<script>
$(document).ready(function(){
$('".$trigger."').".$action."(function() {
".$js_variables."
var ajax_load = '';
var loadUrl = '".$this->controller_path."';
var action = $(this).attr('id');
$('".$this->parent."')
.hide(2)
.html(ajax_load)
.load(loadUrl, {action: action, ".$post_mapper."})
.fadeIn(800);
});
});
</script>
";
echo $script;
?>
Edit: Using a singleton class would also allow me to use $(document).ready() or the shortcut version $(function(){}) only once instead of every single time I add a listener. But I’m not sure if this is worth the extra time and effort… Any ideas?
mm it’s all preference… I generally would do it like this so my text editor would be able to determine what’s javascript and what’s PHP so it wouldn’t make my eyes bleed trying to look at non-code-colored text.