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://php.quicoto.com/tag/jquery/">jQuery</a>. Totally optional */

	/* 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:

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?

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*