Reputation: 32978
I am developing fairly complex webapps/dashboards, mostly in Javascript. I like to use mongo and node on the server, but on the client there is usually an application-specific chaos of libraries and scripts.
My current project includes a combination of bootstrap, jquery, jquery-ui, D3, leaflet, crossfilter and some obscure stuff, and it is fair to say that, although the application is awesome, the code has become an unholy mess. Especially code for D3 and crossfilter is quite verbose, see e.g. source of the official crossfilter demo for a typical example.
So the question: What are good tools and best practices of organizing large javascript applications?
I already avoid global variables and try to organize namespaces with closures, but I am afraid I need some more structure than this. On the server there is npm which is quite nice, but is there something similar in the browser?
I have looked into require.js, backbone.js and coffeescript, but I am not quite sure if these will really solve the problem or only add complexity.
Upvotes: 4
Views: 1412
Reputation: 5335
I think a 'modular' approach is what you need and the use of modules might help you get out of the chaos.
You can have a look at the following:
http://addyosmani.com/largescalejavascript/
http://www.yuiblog.com/blog/2007/06/12/module-pattern/
http://www.2ality.com/2011/04/modules-and-namespaces-in-javascript.html
Upvotes: 2
Reputation: 49693
Sounds like you're already on the right path, but here's a few tips:
Use a framework. Backbone is popular right now, but there's others too. It will significantly help with code organization. In fact, a framework is an absolute must to avoid spaghetti code if your app is of any size at all. Other popular frameworks include Ember and Knockout.
If you decide not to use one of those frameworks, do at least use templating. Such as Mustache or the one built in to underscore.
Combine and minify your files. Mostly to optimize load times. Ideally you'll find something to add to your backend that will do this for you. Rails' "Asset pipeline" for example uses something called Sprockets.
I do hear people raving about coffeescript. It doesn't really add functionality, but those who like it say it makes their code cleaner.
Upvotes: 3