Structuring JavaScript Code

I’ve been a web developer for many years now, yet JavaScript is one of those things I’ve never fully embrassed, mainly because the idea of browser inconsistancies in the content of a programming language really turns me off (the potential frustration is what scares me; HTML and CSS inconsistancies can be frustrating enough). I therefore normaly use a framework like jQuery to take care of cross-browser compatibility. No matter what I use though, there’s always been the problem of structuring the code. Typically, the web apps I create only require minor JavaScript enhancements for basic interaction, etc, so simple procedurel JavaScript works fine, but as I leverage AJAX technologies further, I find myself embedding ever more client-side logic into my pages. Left unchecked I end up with a ball of mud which can be hard to read and maintain.

So, I’m wondering how to best structure my JavaScript code. Typically, the type of JavaScript I write is event-driven like I magine most is. Thus I usually end up with a lot of event handlers. These event handlers can sometimes share a lot of code, and thus I feel compelled to break the logic out into functions or object methods.

Right now I use a Singleton-type object to define common routines. E.g.


App = {
  someProperty: 56,
  someAction: function () {}
}

I usually define all of my event handlers at the top, with my Singleton object defined beneath it. In the ideal world this works, but I often end up a rather monolithic Singleton object which is probably no better than just a pool of functions. I still find the code hard to maintain, and given that the design and behavioural requirements can often changes many times over the life-cycle of a project, I’m hesitant to create any object models to elaborate as they may make future changes even more painful. This makes me wonder how most people structure their client-side JavaScript.

I’m not even sure what I’m asking, I just feel maybe there’s some industry standard’s that JavaScript guru’s use to structure their code, which I’m currently unaware of. I’ve had many years experience with dynamic languages like PHP and Ruby, but that’s always server-side apps, never client-side stuff. Maybe I just need to see some examples of well structured JavaScript so I can get some ideas.

Note: I’m not interested in how to structure generic JavaScript libraries like jQuery for example. I want to know how people structure their actual client-side application code.

Lately I have been wrapping all of mine inside an anonymous function si that they cannot possibly interfere with or be interfered with by anything else in the page.

(function() {
...
})();