Open In App

Module Pattern Implementation in jQuery

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The module pattern is a JavaScript design pattern that promotes encapsulation and organization of code. It uses an IIFE to create a closure that acts as a container for the module’s code. Variables and functions defined within the IIFE are private, while an object literal returned by the IIFE exposes desired properties and methods.           

Note: The Module pattern provides namespacing, information hiding, code reuse, and increased maintainability. It is commonly used in many applications and libraries to write reusable and modular code. The Module pattern provides a clean way to organize code and makes it easier to maintain.

Why Module pattern?

Module pattern in JavaScript encapsulates and organize your code, making it easier to maintain and reuse. The module pattern is used in JavaScript to provide a structure for organizing code into reusable and maintainable modules. It provides a way to encapsulate variables and functions within a single unit of code, making it easier to manage complex applications.

Some benefits of using the Module pattern are as follows:

  • Organizing code: By encapsulating variables and functions within a single unit of code, it’s possible to organize code into smaller, more manageable units. This makes it easier to understand, maintain, and extend code.
  • Creating reusable code: Modules can be easily reused in different parts of an application, reducing code duplication and making it easier to maintain and update code.
  • Implementing data privacy: Variables and functions declared as private in a module are not accessible from outside the module, providing a way to keep data and functionality hidden from other parts of the application.
  • Enhancing code structure: By organizing code into modules, it’s possible to structure code in a way that makes it easier to understand, maintain, and extend.
  • Implementing design patterns: The module pattern can be used to implement other design patterns, such as the Singleton, Factory, and Observer patterns.

Overall, the module pattern is a flexible and powerful tool for organizing and structuring JavaScript code, making it easier to manage, maintain, and test complex applications.

Advantages:

  • Encapsulation: The module pattern provides a way to encapsulate variables and functions within a single unit of code, reducing the likelihood of naming collisions and improving code readability.
  • Reusability: Modules can be easily reused in different parts of an application, reducing code duplication and making it easier to maintain and update code.
  • Namespacing: By organizing code into modules, it’s possible to create a namespace for the variables and functions within the module, avoiding naming collisions with other code and improving code organization.
  • Improved Code Structure: By organizing code into reusable modules, it’s possible to structure code in a way that makes it easier to understand, maintain, and extend.

Disadvantages:

  • Limited Access: Variables and functions declared as private in a module cannot be accessed from outside the module, which can limit the ability to share data and functionality between modules.
  • Performance: The Module pattern uses an Immediately Invoked Function Expression (IIFE) to create a closure, which can have performance implications in some cases, especially in large applications.
  • Debugging: Debugging can be more difficult in the module pattern, as variables and functions declared as private are not accessible from outside the module.

The steps to use the Module pattern:

Create an IIFE: The first step is to create an immediately invoked function expression (IIFE) that will act as a closure for the module’s code.

(function () {
   // Code 
})();

Private variables and functions: Within the IIFE, you can define private variables and functions that are only accessible within the scope of the IIFE. These variables and functions cannot be accessed from outside the module.

(function () {
    var privateVariable = "GeeksForGeeks";
    function privateMethod() {
        console.log(privateVariable);
    }
    // code 
})();

Expose properties and methods: To expose properties and methods to the outside world, return an object literal that contains references to the desired properties and methods.

var myModule = (function () {
    var privateVariable = "I love GFG";
    function privateMethod() {
        console.log(privateVariable);
    }
    return {
        publicMethod: function () {
            privateMethod();
        },
    };
})();

Use the module: You can now use the module by accessing the exposed properties and methods through the object literal returned by the IIFE.

myModule.publicMethod(); 

 Output:

"I love GFG"

Example 1: This code is a JavaScript implementation of a simple “to-do list” application that uses jQuery. When the user clicks the “Add” button, the “addToDo()” method gets executed. The function retrieves the text from the input element, creates a new <li> element with that text, and appends it to the <ul> element. If the input is empty, the function returns without doing anything.

The entire to-do list functionality is contained within an immediately invoked function expression (IIFE), which creates a private scope for the variables and functions defined inside it. The only thing returned from the IIFE is an empty object, which provides a way for the outside code to access some of the functionality inside the IIFE if needed.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>To-Do List</title>
    <link href="style.css" rel="stylesheet">
    <script src=
    </script>
    <script src="to-do-list.js"></script>
</head>
  
<body>
    <h1 class="title">GeeksforGeeks</h1>
    <h3>JavaScript Module pattern</h3>
    <div id="to-do-list">
        <h1>To-Do List</h1>
        <input type="text" id="to-do-input">
        <button id="add-to-do">Add</button>
        <ul id="to-do-list-items"></ul>
    </div>
</body>
  
</html>


style.css: The following stylesheet file is used in the above HTML file.

CSS




.title {
    color: green;
    text-align: center
}
  
h3 {
    text-align: center
}
  
#to-do-list {
    width: 500px;
    margin: 0 auto;
    padding: 20px;
    background-color: green;
}
  
#to-do-list h1 {
    text-align: center;
    margin-bottom: 20px;
}
  
#to-do-list input[type="text"] {
    width: 100%;
    padding: 10px;
    padding-right: 0px;
    padding-left: 0px;
    margin-bottom: 20px;
}
  
#to-do-list ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}
  
#to-do-list li {
    background-color: #fff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
}
  
#add-to-do {
    background-color: black;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}


to-do-list.js: The following JavaScript code is used in the above HTML file.

Javascript




var toDoList = (function ($) {
    var $toDoInput = $('#to-do-input');
    var $addToDo = $('#add-to-do');
    var $toDoListItems = $('#to-do-list-items');
  
    function addToDo() {
  
        // Get the text from the to-do input
        var toDoText = $toDoInput.val();
  
        // Check if the input is empty
        if (!toDoText) {
  
            // If it is, return without
            // doing anything
            return;
        }
  
        // Create a new list item with
        // the to-do text
        var $toDoItem = $('<li>' + toDoText + '</li>');
        $toDoListItems.append($toDoItem);
        $toDoInput.val('');
    }
  
    // Add a click event listener 
    // to the add-to-do button
    $addToDo.click(addToDo);
    return {};
})(jQuery);


Output:

 

Example 2: This JavaScript code creates a module with private and public properties and methods using an Immediately Invoked Function Expression (IIFE). The private variables and functions are defined within the IIFE’s local scope to encapsulate them, and only the public methods are returned as an object. 

This allows for better control of access to private variables and functions. The created module is then assigned to a variable, and its public methods can be called to interact with its private properties.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <script src=
    </script>
</head>
  
<body>
    <script>
  
        // This code defines an immediately invoked
        // function expression (IIFE) which is 
        // assigned to the variable `myModule`
        var myModule = (function () {
            var privateVariable = "I Love GeeksForGeeks";
            var privateArray = [1, 2, 3];
            var privateObject = {
                name: "John",
                age: 30,
            };
  
            function privateMethod() {
                console.log(privateVariable);
            }
  
            function addToPrivateArray(item) {
                privateArray.push(item);
            }
  
            function updatePrivateObject(name, age) {
                privateObject.name = name;
                privateObject.age = age;
            }
  
            return {
  
                // The `publicMethod` property is a function 
                // that invokes `privateMethod`, which logs 
                // the value of `privateVariable`.
                publicMethod: function () {
                    privateMethod();
                },
  
                // The `addToArray` property is a function 
                // that adds an item to `privateArray` and 
                // logs the updated array.
                addToArray: function (item) {
                    addToPrivateArray(item);
                    console.log(privateArray);
                },
                  
                // The `updateObject` property is a function 
                // that updates the properties of `privateObject` 
                // and logs the updated object.
                updateObject: function (name, age) {
                    updatePrivateObject(name, age);
                    console.log(privateObject);
                },
            };
        })();
  
        // The following line calls the `publicMethod` 
        // function on `myModule`.
        myModule.publicMethod();
        myModule.addToArray(4);
        myModule.updateObject("Jane", 35);
    </script>
</body>
  
</html>


Output

I Love GeeksForGeeks
[ 1, 2, 3, 4 ]
{ name: 'Jane', age: 35 }


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads