Good Practice: modular JavaScript

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:

var myProject = myProject || {};

$(document).ready(function () { /* Yes, we're using <a href="https://ricard.dev/tag/jquery/">jQuery</a>. Totally optional */

	/* Init components */
	myProject.components.navigation.init();
	myProject.components.googleMaps.init();
});Code language: JavaScript (javascript)

/components/navigation.js

So, on our common.js we've called the init() function for the navigation component. Let's see what's inhere:

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 componentsCode language: JavaScript (javascript)

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?

Leave a Reply

Your email address will not be published. Required fields are marked *