Today Javascript application of a relevant size become more and more common, and as the need arises, certain patterns are identified to manage the code complexity.
I try to follow good advice, but I have some trouble in organizing the view layer of an application I am writing. While the other layers are nicely decoupled, I have a big blob for the UI that I would like to avoid. To make things clear, I am not talking of application the size Osmani (see the link above) considers - like Gmail - but still big enough to deserve a slightly better architecture.
My problem is that I have a lot of UI elements that I have to place. All these elements can have margins, paddings and so on, and I need to explicitly set their size, as the UI has a lot of constraint that are not expressible by CSS (for instance, some images have to be sized to that an integer number of them appears in a row, without blank space at the end). As if this was not enough, the size of some elements depends on how much space their container allows, and this may depend on the size of other elements and so on.
What I am doing right now is to compute the size of all elements every time the window size changes. I start from the first one, which I can compute freely. As soon as this is placed, I fire an event which trigger the computation of the second one and so on.
This approach more or less works, but is ugly as hell. Every function is full of code like
function resizeFoo() {
var parent = $('#foo').parent(),
parentWidth = parent.width(),
availableWidth = parentWidth - parseInt(parent.css('padding-left'), 10);
$('#foo').width(availableWidth);
}
only much longer. As soon as I add some right padding to #foo's parent, I have to update this. Of course, I could subtract the padding from both sides right from the start, making it event longer.
Are there any useful patterns to handle complex UI sizing and positioning requirements, so that I can reorganize all of the above mess into something meaningful?