After spending the last year with node.js I have come to appreciate JavaScript’s strength as an event driven language, and yet in the browser, beyond binding callbacks to DOM events and AJAX requests, the majority of front-end code seems to be developed in a mostly procedural way.
Recently when faced with taking on a codebase that had grown unmanageable due to the procedural model that had been employed thus far, I began by refactoring the code around a central event dispatcher, allowing many of the large methods — that had previously been created — to be broken down into smaller more loosely coupled pieces.
By introducing an asynchronous model to the code, we were able to break much of it into smaller more maintainable pieces, including a clean break between presentation — such as animations or manipulating the DOM — and the business logic, involving AJAX requests and API calls.
A more loosely coupled system also helped to simplify the development, allowing smaller related sections to be developed independently and by different members of the team.
YUI3 has custom event handling baked in1, and I highly suggest YUI as a framework for any large scale javascript project.
The same technique could be created using jQuery custom events on the document element, although it would be advisable to use one of the dedicated plugins available such as jQuery pubsub by Peter Higgins2.
There are also library agnostic implementations such as the brilliant PubSubJS3 by Morgan Roderick — whom I was fortunate enough to speak with at the fullfrontal4 pre conference drinks earlier this month — and after reading through the code on github I can highly recommend his library.
The exact implementation of this concept does not matter — and will vary massively depending on your choices of framework and libraries — but it should be seriously considered for any medium to large scale javascript project.
© 2010-2012 Daniel Knell