JS Module Design Pattern

Every developer aims to write readable, reusable and maintainable code. Code structuring is more important as applications become larger and scalable. Design patterns is important to solving this challenge .

In JavaScript, a widely used and powerful pattern is the Module Pattern. It is simple to implement. When you look inside the any source code of JavaScript libraries, you’re most likely looking at an implementation of this pattern and they’re most likely a singleton object meaning that only one instance exists throughout the application.

Modules

Modules are an integral piece of code for a project, Module pattern is used to wrap a set of variables and functions together in a single scope. At the end, modules are basically just objects. But there are a couple of ways to create modules.

There are multiple benefits to using module pattern.

Here are the some of them:

  • Maintainability — It helps you maintain your code better. Updating a single module is much easier when the module is separate from other pieces of code.
  • Namespacing — It helps us to avoid polluting the global namespace. it’s common to have namespace pollution, where completely unrelated code shares global variables. In the javaScript language, all variables located outside the scope of top-level functions are global. This means that other code can access them. This is problematic because it creates a situation called namespace pollution.
  • Reusability — It helps us to reuse code, module that we can reuse over and over again.
  • Readability — It helps us to understand code easily.

So lets see a example here.

The Module

Module is just an object. JavaScript variables starting with a lowercase character, but The modules start with an uppercase first character. This is a just convention that helps to read code.

The Settings

In Modules will likely have some significant DOM elements that will need to accessed multiple times. There are many sub-functions in module that do small small things. many of them need this settings elements. so we will make the settings available to each of them.

Init Function

The first thing the init function will do is set the variable s that has declared at the same level as the Module. Where s was declared, this means all functions of the Module will have access to the settings elements.

Bind UI Actions

Bind UI action is a function just for binding the UI events. You never write any code when you bind, you just do the binding and then call another sub-function.

Resource

Like, Share or Leave A Comment!

If you enjoyed this post, don’t forget to give it a 👏🏼, share it with a friend you think might benefit from it and leave a comment! Stay tuned for more exciting blogs on Flutter, Javascript, React, Angular, Ruby, etc.

Thanks

--

--