Maintaining Javascript Code

Pawan Kumar
Squareboat Blog
Published in
2 min readNov 6, 2017

In this post, I will describe how we write scalable and modular Javascript at SquareBoat.

Generally what people do is create one single Javascript file and write code in it.

The approach is OK but it does not do well when your project goes big. This file can go upto 1000+ lines and become difficult to maintain.

Problems

1. There are high chances of getting naming collisions which may break the application in some way.
2. There is no way to make variables private or public.
3. The file can get really long which is difficult to maintain when projects scales up.
4. The code is not modular at all.

So to write modular javascript code, we use object module pattern described in the book — Javascript Design Pattern by Addy Osmani.

Object Module Pattern

Following is the template for Object Module pattern.

This template is from the book itself.
Notice we are creating a function and immediately calling it and storing it in a variable which is an object that has access to public variables / functions.

Now let me show you how we use this pattern for actual projects.

Previously we had only one file for the entire project. But now we will create one file for each entity that is in the project. For e.g — user.js for all user page related codes, category.js for category related pages etc.
For all common code, we create one file called ui.js.

Here is the template for user.js

Notice we are returning only the init method from the function. So our users variable will have access only to init method. All other variables will be private and won’t create any naming collision.

We also create init.js that will call the init methods of all modules.

Now our init methods call the bindEvents which will have all binding of events like attaching click event handlers, form submit event handlers, etc.
Notice the use of require() function. It is not supported in javascript by default. We use webpack to make it work.

All of your DOM event listeners will be defined in bindEvents() method which will be called by init() function.
So whenever require(‘./users’).init() is called, all of our event listeners are binded.

So our js folder will now have following structure.

├── comments.js
├── categories.js
├── init.js
├── ui.js
└── users.js

Also we use webpack as our module bundler so that we can use require() functionality and compile all of these files into one single minified javascript file.

This approach has been going good for us so far. Hope it might have our fellow coders also in some way.

Happy Coding :)

--

--