Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presentational js vs. functional js: Separate them? General architecture?

This is a general kind of question.

Very often, I need to write JavaScript for web pages. Keeping in mind best practices, unobtrusive js, etc. I have my JavaScript in separate *.js files. Every page gets its own js file. What's been somewhat bothering me lately, is the mix of presentational code with functional code that I always end up with.

So, for example, I would assign a .click handler to an element. On that click the element must change its appearance and an AJAX call must be made to the server. So, right now, I'd do both of these things inside that .click handler. It might get bulky depending on what needs to be accomplished. When I come back to these blocks of code after not touching them for a week, I often feel like it takes away too much time to trace through all lines of code when I only need to fix something with appearance.

Anyway, any idea on architecture/design for presentational js vs. functional js? Keep them in one file, but break into separate functions? Break them into 2 separate files? Leave them alone?

like image 494
Dimskiy Avatar asked Aug 03 '10 15:08

Dimskiy


1 Answers

I find it useful to have three JS files in each dynamically generated page. The general functions that are re-used everywhere, the project specific functions that are used all over the project and the page specific js file. This way you have a handle on what is "reusable" and what isn't. This also encourages you to "promote" your code.

As you "promote" it, you will find yourself separating it more and more into UI or Behavior. As more stuff gets separated you may find yourself including 6 files or just breaking each file up with a package structure as you suggested earlier UIFunctions().doStuff()... However if you have to prefix your stuff with PageName you haven't promoted your code and maybe it is time you do so :-)

That is just how I have been doing it.

like image 63
David T Avatar answered Oct 30 '22 17:10

David T