DEV Community

Krishna Kant Sharma
Krishna Kant Sharma

Posted on

First Experience with Javascript Design Pattern: Calorie Tracker Application

Encapsulating Your Code With Modular Approach

I just Completed with My Advance javascript parts like ES6 and Modules so I decided to push it one level further, I read about Javascript Patterns which are helpful to right clean proper and modularize codes so I decided to learn them and work on them. I hereby share my journey with all of you with Javascript Pattern so far.

In Javascript, there is a widely used pattern “Module Revealing Pattern/Module Pattern”. It may be a new Challenge for me to learn and implement a completely new pattern of writing code as several variations exist. But at the last when I came to know more about it, I understand it’s worth time and trouble because you’ll be using this pattern very often to make your app more robust.

So the First thing which came in the picture

1. Modules

Javascript Comes with a very clean sugar syntax for your codes it allows you to create modules for different aspects. Modules are bust objects. but you can create them in many ways.
The most basic way is to assign an object to a variable

let moduleObject = {
      doSomething(){
       console.log('doSomething');
     }
}

2. Immediately Invoked Function Expression

It is a special kind of function which run immediately after javascript loads and returns an object which then becomes the module
It is a kind of structure to encapsulate your code within the module and reveal only that part which is useful or want to share, You can share all the functions and variables and return them within the object which you wanted to make public

let something = (function(){
let private;
function doSomethingPrivate(){
      Do something...
   }

   return{
      var publicFunction = function(){
          doSomethingPrivate();
      }
   }
})();

This is the Basic Structure of an IIFE or you can say a Module

Accessing the Module

We can access the function publicFunction() outside the IIFE And it works properly But if you try to access doSomethingPrivate() outside the IIFE you received an error. This way you can encapsulate your private variable and functionally dependent activities
Revealing Module Pattern
As shown in module pattern creating another public function and revealing it in spite of you can also reveal your function written as an Object property, I.e you can return an object and set functions to its property following the same name or the name you want
Let me show you an example the get the clear picture of revealing module pattern
Here I can make a controller like a module similar to the database controller

let useController = (function(){
let users = [ ]
function addUser(user){      
           users.push(user);
           console.log(‘User added.!!’);
     }
function getUser(id){     // Return user after matching id
          return users.find(item => {
              Return Item.id === id;
          });
     }
return {
         addUser : addUser,
         getUser : getUser
     }
})();
My Implementation on Module Revealing Pattern

I Have Created a Calorie Tracker app using Module Revealing design Pattern
Github Project: https://github.com/krishna7860/Calorie-Tracker
I Start With Distributing My Modules For Every task so I decided to create a total of four modules, One for User Interface functionalities and for handling Food Item I created an Item Controller Module, One controller for persisting data to local storage and lastly I created on main module to handle all the work which is App Controller Module

Item Controller Module

In Item Module I created an abstract Data structure to store my data so I decided to make my own which will make manipulation easy

const data = { 
   item: StorageCtrl.getItemsFromStorage(),
   currentItem: null,
   totalCalories: 0
};
This is handling all the items and current item and the total calories count
Functions in Item Controller
function getItem(){
    return an item
}
function addItem(){
    add Item to DataStructure
}

And Many More Functions Related to Item Manipulations
You can refer to code there are so many so I am not comfortable to write them all here
Storage Controller Module
Storage Module can handle all the operations related to local storage adding the item to local storage, updating the state of the app after webpage refreshes

const StorageController = (function(){

    function storeItem();
function getItemsFromStorage();
function updateItemStorage();
function deleteItemFromStorage();
function clearItemsFromStorage();
})();

UI Controller Module

UI Module handles all the operations related to UI it handles the state of the main input form which can be toggled within in the code execution while adding and editing the item in the food list. there are two states

1. Add Item State

while Adding a new item there is only one button visible

2. Update Item State

Update Item State will change the main form and add three-button one for update and delete and back and insert list data to input fields

App Controller Module

This module can handle all the operations related to adding event listeners, it has a special Object which has all the UI selectors element to access HTML element in Javascript easily
It Handles all the callback operations related to data while adding, deleting, updating and clearing data, which operation to be done first and what should be called after the particular operation, I extremely suggest refer to code it is well written with comments
It Has the instance of all the modules passed in as an argument to access all the feature and function of all previous modules

const App = (function(ItemCtrl, UICtrl, StorageCtrl) {
function loadEventListners(){}      //Loading all Listners
function itemAddSubmit(){}          // Adding Item on Click

      function backItem(){}             // When Back Buttons pressed
function itemEditClick(){}          // When Edit state Occurs
function itemUpdateSubmit(){}       // Updating Item
function itemDeleteSubmit(){}       // Deleting Item
At last, Using the App.init() function to load all the modules
App.init();                               //Init all the 
Modules

Conclusion

That's All, for now, I had a great learning experience with Module Design Pattern I wish to explore more in javascript cause it is my favorite language to code. Next, I am moving towards the ES 2015 Modules and also going to create a project using it.

Top comments (0)