1

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?

1 Answer 1

1

Yes is for DRY, image example: function bar for example set width or calculate width for some other elements and he is immedly invoked, for calculate width for initial. But when window is resized You must do recalculate so you bind that function to event resize.

Good example for put function in function is Module pattern: link to good free ebook to learn javascript patterns

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link, its a great book!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.