When we all begin with JavaScript we start writing big-ass files, all the functions on the same place, hoping we'll never have to edit again. It's basically: "good luck future me if you have to debug this thing". Hundreds of lines and chaos.
Well, there's a better way to do things. Let's use a modular approach, we'll create components and call them as necessary.
common.js
Here we'll place all the calls to components. Something like this:
1 2 3 4 5 6 7 8 9 10 |
var myProject = myProject || {}; /* Init components */ myProject.components.navigation.init(); myProject.components.googleMaps.init(); }); |
/components/navigation.js
So, on our common.js we've called the init() function for the navigation component. Let's see what's inhere:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
var myProject = myProject || {}; myProject.components = $.extend(myProject.components, { "navigation": (function() { var $that = this; this._init = function($scope) { /* Do something */ }, // init this._anotherFunction = function() { /* Do something else */ } // _anotherFunction return { init: $that._init, anotherFunction: $that._anotherFunction } })() // END navigation }); // END of components |
We'll make use of the $that approach inside our components.
How do you handle your JavaScript?
In those projects where you're not using things like AngularJS, how do you work with plain JavaScript code?