At the moment I am trying so write better code by paying more attention to structure & patterns. Out of interest I started to look at other people's code to see how they have structured it. One 'pattern' I came across multiple times is something like this:
function foo(a, b) {
function bar() {
// do something with a & b
}
bar();
// event handler, e.g. resize
$(window).on('resize', bar);
}
$(document).ready(function () {
foo(a, b);
});
So a function is defined and e.g. two values are passed to that function. In that function, another function is defined where something is done with the two values. That second function is then attached to an event handler (the resize event is just an example). Finally, the outer function is fired when the DOM is ready.
Why do people write their code like this, just to keep the document ready function nice and clean? Or to stop people from binding there function to another event? Maybe it has something to do with variable scope?
Also, why fires bar
before the event handler is attached, is this some kind of init to set values and then only adjust them when a certain event occurs?