The module pattern

So we understand how we must breakup the code, but how do we organize it? So far 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 so far and create a new file for it at src/NewInvestmentView.js:

(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 so far. 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 a new scope to create 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 a parameter. In this example it is already passing three dependencies to the NewInvestmentView code: jQuery, Investment, and Stock.

As you can see by 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.

And if we need to make anything global, we do that explicitly by attaching it with the global object:

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.

And although this practice has not much 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 knows as the module pattern , and we will be using it throughout the rest of 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
3.144.113.163