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...