I’m a bit confused at the moment regarding how to have a more maintainable javascript architecture. I might be out of the track, but I would say that almost 50% of my code involves the DOM hence use my base library (jQuery).
I’ve checked [1] Nicholas Zakas’ scalable application architecture design: http://developer.yahoo.com/yui/theater/video.php?v=zakas-architecture and [2] Addy Osmani Patterns For Large-Scale JavaScript Application Architecture http://addyosmani.com/largescalejavascript/ .
I have a one page application style, with lots of content being fetched via ajax and DOM elements being added dynamically. My main question is: How can I separate the code into small re-usable blocks if I’m using jQuery (or any other base library) to manipulate the DOM.
Let’s just pick a task list module for example. I understand that the module could look like this:
var TaskList = function() {
addTask = function() {
...
};
removeTask = function() {
...
};
return {
addTask: addTask,
removeTask: removeTask
}
}();
Where should the DOM elements events registration be written, the ajax call to save, load, or delete a task, appending a new task to a DOM element, etc.
I have no problem committing to having jQuery on the module as a dependency, but if there is a better way I think I missed it from the two resources above and I would love to know it.
I just want to have a more elegant way of maintaining the growing javascript because I’m tired of spaghetti 😉
Thanks for your time!
Since you are going to develop a single page application you are going to have many visual modules that will be displayed at a current step and then they will be replaced by others.
You can follow the MVC pattern (Model-Controller-View), with each visual element being a separate entity with its own code for DOM manipulation and the business logic stored in separate classes.
One way would be:
The main container can hold all the smaller container, with everyone accommodating a different view controller that has it’s own DOM manipulation code, (which also has the benefit of being able to be loaded dynamically on demand and so reduce your initialize load time).
Every view can have a couple module that will perform the ‘actions’ and which will communicate with a third module (optional) that will take care of the I/O with databases, sockets, files, etc.
Hope it helped!