Practice exercises CHAPTER 6 301
$(this).text() : $('#txtInput').val() + $(this).text());
};
- Convert the plusClick method to use jQuery.
You must call the clearEntry method, but you can’t use the this keyword to call
clearEntry because the clicked button is referenced by this. Because there is only one
copy of the clearEntry method, and it’s on the prototype, call the clearEntry method
from the Calculator prototype. Your code should look like the following.
Calculator.prototype.plusClick = function () {
$('#txtResult').val(Number($('#txtResult').val()) +
Number($('#txtInput').val()));
Calculator.prototype.clearEntry();
}; - Convert the minusClick method to use jQuery.
Your code should look like the following.
Calculator.prototype.minusClick = function () {
$('#txtResult').val(Number($('#txtResult').val()) -
Number($('#txtInput').val()));
Calculator.prototype.clearEntry();
}; - Convert the clearEntry method and the clear method to use jQuery.
The completed CalculatorLibrary.js file should look like the following.
///
(function () {
this.calculatorNamespace = this.calculatorNamespace || {};
var ns = this.calculatorNamespace;
ns.initialize = function () {
var calculator = new ns.Calculator();
$('button[id^="btnNumber"]').on('click', calculator.numberClick);
$('#btnPlus').on('click', calculator.plusClick);
$('#btnMinus').on('click', calculator.minusClick);
$('#btnClearEntry').on('click', calculator.clearEntry);
$('#btnClear').on('click', calculator.clear);
calculator.clear();
}
ns.Calculator = (function () {
function Calculator() {
}
Calculator.prototype.numberClick = function () {
$('#txtInput').val($('#txtInput').val() == '0'?
$(this).text() : $('#txtInput').val() + $(this).text());
};