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.
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.
At this point, I have some HTML and an empty app.js file.
Let’s start with the application itself. Following the structure mentioned above, here is the shell for our application.
Now, let’s add some functionality to our app:
Here, I added one property,
title and two functions,
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:
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.
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.
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.
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.
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.
ready function as shown below:
and here is the console output of these operations:
Credit: Source link