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 t开发者_StackOverflow中文版o debug and this made harder because I have event listeners littered across the HTML.
The code handles AJAX calls and DOM manipulation.
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.
You may consider to use CommonJS "require" to separate javascript code in many files, then use browserify or Webpack. Another option is Cor which is a language that compiles to javascript focused on organization, cleanness, and development experience.
精彩评论