DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Better Scaffolding with jQuery - Part I
  • An Introduction to Type Safety in JavaScript With Prisma
  • DocRaptor vs. WeasyPrint: A PDF Export Showdown
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users

Trending

  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • Is the Data Warehouse Dead? 3 Patterns From Enterprise Architecture That Answer This Question
  • Implementing Observability in Distributed Systems Using OpenTelemetry
  • Migrate a Hardcoded LangGraph Agent to LaunchDarkly AI Configs in 20 Minutes
  1. DZone
  2. Coding
  3. JavaScript
  4. Structure JavaScript Code

Structure JavaScript Code

We will learn how to structure JavaScript code using Revealing Module pattern.

By 
Jawad Hasan Shani user avatar
Jawad Hasan Shani
DZone Core CORE ·
Apr. 28, 21 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
19.7K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

Modern JavaScript frameworks like Angular, Vue, etc. have a built-in mechanism to structure JavaScript code. When not using these frameworks, we can use simple techniques to structure our JavaScript. In this post, I will show you one of them using the Revealing Module pattern.

This pattern is very popular and there are a great many resources online utilizing this design and here I will try to share a simple implementation of the same.

Why Structure JavaScript Code

Encapsulated and modular-based JavaScript code promotes reusability and is better for maintenance.

To avoid spaghetti JavaScript all over the code base, a Revealing Module pattern shall be used to structure JavaScript code.

Following are some of the benefits of using this pattern:

  • “Modularize” code into re-usable objects.
  • Variable/functions taken out of the global namespace.
  • Expose only public members.
  • 'Cleaner' way to expose public members.

Revealing Module Structure

Here is an example of kind of the standard format and structure for the Revealing Module pattern.

Revealing Module Pattern Structure

Initial Setup

Before we dive into JavaScript code, let’s talk about the initial development environment setup. I am using a very basic JavaScript project for the demo, it just has a single HTML page, some CSS styles, and a basic dev server. For more information, please check the Basic Front-end Dev. Environment Setup post. This will set up a starting point for us to move forward.

At this point, I have some HTML and an empty app.js file.

HTML in app.js File

App JavaScript Code

Let’s start with the application itself. Following the structure mentioned above, here is the shell for our application.

JavaScript
 




x


 
1
var app = function () {     
2
    //private members 
3
  
4
    //public API    
5
  return {  
6
    
7
     };
8
  
9
}();



Now, let’s add some functionality to our app:

JavaScript
 




xxxxxxxxxx
1
20


 
1
var app = function () {
2

          
3
    //private members
4
    title = 'Structure JavaScript';
5

          
6
    displayTitle = function(){
7
        alert(this.title);
8
    }
9

          
10
    displaySite = function(){
11
        alert('site info...');
12
    }
13

          
14
    //public API
15
    return {
16
        title:title,
17
        displayTitle: displayTitle
18
    };    
19

          
20
}();



Here, I added one property, title and two functions, displayTitle() and displaySite(). Then in the public API section, I exposed the title property and one function. Notice that I did not expose the displaySite function and this illustrates a private function that shall not be accessible from outside of this code block.

Next, I added the following code in the document.ready in index.html as shown below:


JavaScript
 




xxxxxxxxxx
1


 
1
  <script>
2
    $(document).ready(function () {
3
      console.log(app.title);
4
      app.displayTitle();
5
      app.displaySite();//this will not work
6

          
7
    });
8
  </script>



Now, if you run the npm start command and go to browser page, you will see that the first two lines works and the third line app.displaySite() does not work, which is expected.

So, this is the general idea of this pattern. It helps us organize our JavaScript code while not polluting the global namespace.

Next, let’s see how we can use this pattern to consolidate AJAX calls.

Consolidating AJAX Calls

In order to eliminate scattered Ajax calls throughout the code, we can use Revealing Module Pattern to consolidate Ajax calls.

Developers can create a data-services script and use Ajax promises for success and failure scenarios via callbacks.

Typically a project will have more than one data service and not repeat the boilerplate Ajax code. we can refactor the actual Ajax calling part into another JavaScript object called, ajaxService and, you guessed it right, we can use the Revealing Module pattern for this service as well.

ajaxService will be a low-level implementation detail and it will handle all types of Ajax calls. While Data-Services will use the ajaxService to perform data-related operations.

ajaxService Implementation

Here is a simple implementation of ajaxService (ajaxService.js). It just has one method which takes some input and returns a promise which calling code can then use for making Ajax calls.

JavaScript
 




xxxxxxxxxx
1
28


 
1
var ajaxService = function () {
2

          
3
    makeAjaxRequest = function (httpMethod, url, data, async, cache) {
4

          
5
        if (typeof async == "undefined") async = true;
6
        if (typeof cache == "undefined") cache = false;
7

          
8
        var ajaxObject = $.ajax({
9
            type: httpMethod.toUpperCase(),
10
            url: url,
11
            data: data,
12
            datatype: 'json',
13
            async: async,
14
            cache: cache,
15
            beforeSend: function (request) {
16
                request.setRequestHeader("content-type", "application/json")
17
            }
18
        });
19

          
20
        return ajaxObject;
21
    }
22

          
23
    //public API
24
    return {
25
        makeAjaxRequest: makeAjaxRequest
26
    };
27

          
28
}();



DataService Implementation

I created another JavaScript file called dataService.js with the following code:

JavaScript
 




xxxxxxxxxx
1
21


 
1
var dataService = function () {
2

          
3
    let getUsersUrl = 'https://reqres.in/api/users?page=2';
4
    let createUserUrl = 'https://reqres.in/api/users';
5

          
6
    getUsers = function () {
7
        //return a promise
8
        return ajaxService.makeAjaxRequest('GET', getUsersUrl, null)
9
    }
10

          
11
    createUser = function (userObject) {       
12
        return ajaxService.makeAjaxRequest('POST', createUserUrl, userObject);
13
    }
14

          
15
    //public API
16
    return {
17
        getUsers: getUsers,
18
        createUser: createUser
19
    };
20

          
21
}();



It is also using the Revealing Module pattern and the code is simple. This service uses ajaxService internally. Note that I am using a publicly available test backend on the internet and making Ajax calls to it. You can use your own REST API by replacing the endpoints (URLs).

App.js Code Update

I created new methods in app.js file and these methods use dataService for their operations.

New Methods in app.js File


Application Bootstrap

I also referenced these JavaScript files in the index.html page and updated the ready function as shown below:

Updating index.html

and here is the console output of these operations:

Console Operation Output

Summary

The Revealing Module pattern can help structure JavaScript code. It has limitations, but for simple codebases, this can work very well. You can download the demo code from this git repo. Let me know if you have any comments or questions. Till next time, Happy Coding!

JavaScript code style

Published at DZone with permission of Jawad Hasan Shani. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Better Scaffolding with jQuery - Part I
  • An Introduction to Type Safety in JavaScript With Prisma
  • DocRaptor vs. WeasyPrint: A PDF Export Showdown
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook