Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

298 CHAPTER 6 Essential JavaScript and jQuery


Your code should look like the following.
/// <reference path="_references.js" />

(function () {
this.calculatorNamespace = this.calculatorNamespace || {};
var ns = this.calculatorNamespace;

//existing code here....

})();


  1. Remove the variables that reference txtInput and txtResult because jQuery will be used
    to access these DOM elements as needed.
    The initialize function will remain in the namespace.

  2. Surround the numberClick, plusClick, minusClick, clearEntry, and clear functions with
    an IIFE that is assigned to a Calculator property in calculatorNamespace.
    Your code should look like the following.
    ns.Calculator = (function () {


function numberClick() {
txtInput.value = txtInput.value == '0'?
this.innerText : txtInput.value + this.innerText;
}

function plusClick() {
txtResult.value = Number(txtResult.value) + Number(txtInput.value);
clearEntry();
}

function minusClick() {
txtResult.value = Number(txtResult.value) - Number(txtInput.value);
clearEntry();
}

function clearEntry() {
txtInput.value = '0';
}

function clear() {
txtInput.value = '0';
txtResult.value = '0';
}
}());


  1. Add a Calculator function inside the IIFE, which will be the constructor function. There
    is no code for the constructor at this time. At the bottom of the IIFE, add code to
    return this constructor function. Try this on your own, but if you have a problem, the
    sample code is shown in step 10.

Free download pdf