Modular JavaScript Design Pattern
We have a simple webpage that adds to two fields together and displays the result.
Here is the following JavaScript for the interaction.
var first = document.querySelector('#num1'),
second = document.querySelector('#num2'),
display = document.querySelector('#result');function calculate() {
var result = parseInt(first.value) + parseInt(second.value);
display.innerHTML = result;
}
As you can see the function calculate() handles several responsabilities. It fetches the values from the DOM, sums the two values together and parse them and even insert the result back into the DOM.
We have DOM manipulation and logical tangled together
Let's extract the logic from this public function into a separate module.
// APPLICATION NAMESPACE
App = {};// MODULE JAVASCRIPT DESIGN PATTERN
App.Calc = (function() {
var add = function(num1, num2) {
return parseInt(num1, 10) + parseInt(num2, 10);
};
return {
add: add
};
}());
var first = document.querySelector('#num1'),
second = document.querySelector('#num2'),
display = document.querySelector('#result');
function submitForm() {
display.innerHTML = App.Calc.add(first.value, second.value);
}
We created a module called App that encapsulates the logic into the namespace and defines the public api add. This module now is self contained and it can be reused and enhanced.