tags:

views:

81

answers:

2

My MVC controller is in charge of passing desired onload javascript to my view object which inserts it into the bottom of my main page template.

My question is...should I store the actual onload js scripting in my controller, or should i store it in my model, and have the controller pull it from there?

My confusion is rooted in the fact that its not really business logic...

Option 1:

/* --- js store in my controller --- */
$page->add_js_onload('various jquery scripting');

Option 2:

/* --- js fetched from my model --- */
$page->add_js_onload($this->model->fetch_onload_js());

Which is cleaner and more scalable (or just more elegant)?

+2  A: 

You should definitely do this in your controller. But I would only pass the name of a Javascript file to the view and load this in your view with the HTML script tags.
This makes it easier to maintain your Javascript code.

Only put code in your model that is business logic and closely model related.

Felix Kling
+1 for saying what I was going to, and more concisely.
iandisme
+2  A: 

You're absolutely right when you say "it's not really business logic." When doing MVC for the web you should consider JavaScript code a view or a partial view (e.g. /views/mywidget/myfile.js.php--in which case you can load dynamic data into it if you need to), or a separate entity entirely (e.g. /public/js/myfile.js, which you'll include in your view with a script tag). The specifics depend on what MVC framework you're using.

Keeping actual JS code in your controller or model goes against MVC principles just as much as putting HTML code there.

Jordan
so what you are saying is have a separate view for the page's js, and then i can configure it throught the controller, and then inject it into the html view?
johnnietheblack
Yes, basically, although I think it's usually better to load JS as a separate file (<script src="...">) so that the browser can cache it separately from the page. This would probably require another action in your controller, though.
Jordan
I would say just keep an array of JS file names. Where you inject the javascript into your template you do s.th. like '<?php foreach($file in $page->jsFiles) :?> <script src=".../<?php echo $file ?>" /> <?php endforeach; ?>
Felix Kling