Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organization JavaScript code in project for maintainability?

Am primarily a PHP developer, but of late I've being playing with alot of JavaScript, mostly in jQuery.

The problem is that the code is getting harder to debug and this made harder because I have event listeners littered across the HTML.

The code handles AJAX calls and DOM manipulation.

like image 570
MrFoh Avatar asked Sep 24 '11 22:09

MrFoh


1 Answers

Separation of concerns

This means you have three types of files, HTML, CSS and JS.

You do not mix any HTML, CSS or JS. Each one of them is in its own file.

Merely by keeping everything seperate and never using inline javascript or inline CSS you can solve most your code organization problems.

Another technique is packagers and minifiers.

My packagers of choice are browserify (js) and less (css)

Packagers mean you have all your code in many files/modules split by good design. Then because sending many small files is expensive you use a build-time packager to turn all your js into one js file and all your css into one css file.

As for JS itself, I tend to go further and use a module loader. Browserify is both a packager and a module loader.

Module loaders mean you define small modules and load/require them when you need to and where you need to.

I also implement event driven architecture and the mediator pattern to keep my code highly loosely coupled. One could go further and implement something like the blackboard system but I havn't tried this personally.

like image 178
Raynos Avatar answered Sep 22 '22 08:09

Raynos