The module pattern

So, we understand how we must break up the code, but how do we organize it? Until now, we have created a file for each new function. This is a good practice, and we are going to see how we can improve on that.

Let's start by thinking about our NewInvestmentView component. We can follow the pattern we've used until now and create a new file, NewInvestmentView.js, and place it in the src folder, as follows:

(function ($, Investment, Stock) {
  function NewInvestmentView (params) {

  }

  this.NewInvestmentView = NewInvestmentView;
})(jQuery, Investment, Stock);

You can see that this JavaScript file is more robust than the examples shown until now. We have wrapped all the NewInvestmentView code inside an immediately invoked function expression (IIFE).

It is called an IIFE because it declares a function and immediately invokes it, effectively creating new scope to declare local variables in.

A good practice is to use only local variables inside the IIFE. If it needs to use a global dependency, pass it through as a parameter. In this example, it is already passing three dependencies to the NewInvestmentView code: jQuery, Investment, and Stock.

You can see this at the function declaration:

function ($, Investment, Stock)

And immediate invocation:

})(jQuery, Investment, Stock);

The biggest advantage of this practice is that we no longer need to worry about polluting the global namespace since everything we declare inside the IIFE will be local. This makes it much harder to mess with the global scope.

If we need to make anything global, we do that explicitly by attaching it with the global object, as follows:

this.NewInvestmentView = NewInvestmentView;

Another advantage is the explicit dependency declaration. We know all about a file's external dependencies by glancing at its first line.

Although this practice does not have a great advantage right now (since all of the components are being exposed globally), we are going to see how to benefit from it in Chapter 8, Build Automation.

This pattern is also known as the module pattern, and we will use it throughout the rest of the book (even though sometimes it is omitted for simplification purposes).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset