Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you organize your Javascript code?

Tags:

When I first started with Javascript, I usually just put whatever I needed into functions and called them when I needed them. That was then.

Now, as I am building more and more complex web applications with Javascript; taking advantage of its more responsive user interaction, I am realizing that I need to make my code more readable - not only by me, but anyone who replaces me. Besides that, I would like the reduce the moments of 'what the heck, why did I do this' when I read my own code months later (yes, I am being honest here, I do have what the heck was I thinking moments myself, although I try to avoid such cases)

A couple weeks ago, I got into Joose, and so far, it has been good, but I am wondering what the rest do to make their chunk their codes into meaningful segments and readable by the next programmer.

Besides making it readable, what are your steps in making your HTML separated from your code logic? Say you need to create dynamic table rows with data. Do you include that in your Javascript code, appending the td element to the string or do you do anything else. I am looking for real world solutions and ideas, not some theoretical ideas posed by some expert.

So, in case you didnt't understand the above, do you use OOP practices. If you don't what do you use?

like image 983
DLS Avatar asked Aug 28 '09 01:08

DLS


People also ask

How is JavaScript structured?

JavaScript programs consist of a series of instructions known as statements, just as written paragraphs consist of a series of sentences. While a sentence will end with a period, a JavaScript statement often ends in a semicolon ( ; ).

What are JavaScript files?

What is a JS file? JS (JavaScript) are files that contain JavaScript code for execution on web pages. JavaScript files are stored with the . js extension. Inside the HTML document, you can either embed the JavaScript code using the <script></script> tags or include a JS file.


1 Answers

For really JS-heavy applications, you should try to mimic Java.

  • Have as little JS in your HTML as possible (preferably - just the call to the bootstrap function)
  • Break the code into logical units, keep them all in separate files
  • Use a script to concatenate/minify the files into a single bundle which you will serve as part of your app
  • Use JS namespaces to avoid cluttering up the global namespace:

 

var myapp = {};  myapp.FirstClass = function() { ... };  myapp.FirstClass.prototype.method = function() { ... };  myapp.SecondClass = function() { ... };  

Using all these techniques together will yield a very manageable project, even if you are not using any frameworks.

like image 71
levik Avatar answered Sep 21 '22 16:09

levik