Yesterday, we covered how to use javascript libraries.
Today, I want to add a bit of information on structuring your javascript code.
I'm going to dicuss Modularity.
The degree to which a system's components may be separated and recombined.
var myModule = (function() { var vm = {}; // module code implemented here return vm; })();
The vm variable refers to the term "View Model".
See this little thing on the end of our module?
...}());
We define the module by setting properties on the view model vm.
We can define module variables:
vm.counterValue = 0;
We can define module functions:
vm.increment = function() { // ... }
You can also define variables and methods that are only available in the module.
var youCantSeeMe = "this is my own variable"; function youCantCallMe(p1) { return "You can't call me"; }
This keeps the scope of youCantSeeMe and youCantCallMe within the module, and not viewable or callable from outside.
<div id="counter"> <div id="result"></div> <button id="subtract">-</button> <button id="add">+</button> </div>
And yesterday's implementation (non-jQuery):
var result = document.getElementById("result"); var addButton = document.getElementById("add"); var subtractButton = document.getElementById("subtract"); addButton.addEventListener('click', function(){ result.innerHTML = parseInt(result.innerHTML) + 1; }); subtractButton.addEventListener('click', function(){ result.innerHTML = parseInt(result.innerHTML) - 1; });
var counter = (function() { var vm = {}; var value = 0; // private! vm.init = function(addButton, subtractButton, resultArea) { vm.addButton = addButton; vm.subtractButton = subtractButton; vm.resultDiv = resultArea; vm.addButton.addEventListener('click', vm.add); vm.subtractButton.addEventListener('click', vm.subtract); vm.resultDiv.addEventListener('valueUpdated', vm.display); vm.reset(); } vm.add = function() { value++; vm.display(); } vm.subtract = function() { value--; vm.display(); } vm.reset = function() { value = 0; vm.display(); } vm.display = function() { vm.resultDiv.innerHTML = value; } return vm; }()); counter.init( document.getElementById('add'), document.getElementById('subtract'), document.getElementById('result') );
CodePen Example: http://codepen.io/tamouse/pen/rebvyP
var counter = (function() { var vm = {}; var value = 0; // private! vm.init = function(displayArea, incrementer, decrementer) { vm.displayArea = displayArea; vm.incrementer = incrementer; vm.decrementer = decrementer; vm.incrementer.on('click', vm.add); vm.decrementer.on('click', vm.subtract); vm.reset(); } vm.add = function() { value++; vm.display(); } vm.subtract = function() { value--; vm.display(); } vm.reset = function() { value = 0; vm.display(); } vm.display = function() { vm.displayArea.text(value); vm.displayArea.addClass("changing"); setTimeout(function() { vm.displayArea.removeClass("changing"); }, 1000); } return vm; }()); counter.init($('#result'), $("#add"), $('#subtract'));;
Codepen Example: http://codepen.io/tamouse/pen/EKJpyQ