How to structure my javascript/jquery code?

I am toying around with a pretty intensive ajax based jquery web application. It is getting to a point where I almost loose track of what events that should trigger what actions etc.

I am sort of left with a feeling that my javascript structure is wrong, on a more basic level. How do you guys structure your javascript/jquery code, the event handling etc., any advise for a newbie javascript developer.


AMDS!

It's been awhile since first answers got posted to this question and many things have changed. First and foremost, the JS browser world seems to be moving towards AMDs (asynchronous module definition) for code organization.

The way that works is you write ALL your code as AMD modules, e.g.:

define('moduleName', ['dependency1', 'dependency2'], function (dependency1, dependency2) {
    /*This function will get triggered only after all dependency modules loaded*/
    var module = {/*whatever module object, can be any JS variable here really*/};
    return module;
});

And then modules get loaded using AMD loaders like curl.js or require.js etc, for example:

curl(
    [
        'myApp/moduleA',
        'myApp/moduleB'
    ],
).then(
    function success (A, B) {
        // load myApp here!
    },
    function failure (ex) {
        alert('myApp didn't load. reason: ' + ex.message);
    }
);

Advantages are:

  1. You only have to include single <script> element on your page that loads AMD loader itself (some of them are quite tiny).

  2. After that all JS files will be fetched automatically in asynchronous NON BLOCKING! fashion, thus way faster!

  3. Necessary modules will get executed only after its dependencies got loaded.

  4. Modular (which means code that is easier to maintain and re-use).

  5. Global variables pollution can be completely curbed if used correctly.

Honestly, once concept has clicked in your head, you'll never go back to your old ways.

P.S: jQuery does register itself as AMD module starting from version 1.7.

More information on AMDS:

  • https://github.com/cujojs/curl
  • http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition
  • http://requirejs.org/
  • http://www.bennadel.com/blog/2275-Using-RequireJS-For-Asynchronous-Script-Loading-And-JavaScript-Dependency-Management.htm
  • https://github.com/Integralist/Blog-Posts/blob/master/2012-01-04-Beginners-guide-to-AMD-and-RequireJS.md

For javascript code I found the following links from Christian Heilmann indispensable

  • The module pattern
  • Configuring scripts

I also really like the method described by Peter Michaux here

For jQuery, I heartily recommend reading the guides on Authoring and I found this tutorial on jQuery plugin patterns very good