KnockoutCalculator

by charmis

HTML

<table border='1'>
    <tr>
        <td>
            <span data-bind='text: currentOperand' style='float:right'>&nbsp;</span>
        </td>
    </tr>
    <tr>
        <td>
            <table>
                <tr>
                    <td><button id='no1' data-bind='event : {click: numberClick}'>1</button></td>
                    <td><button>2</button></td>
                    <td><button>3</button></td>
                    <td><button data-bind='click: add'>+</button></td>
                    <td><button data-bind='click: subtract'>-</button></td>
                </tr>
                <tr>
                    <td><button>4</button></td>
                    <td><button>5</button></td>
                    <td><button>6</button></td>
                    <td><button>*</button></td>
                    <td><button>/</button></td>
                </tr>
                <tr>
                    <td><button>7</button></td>
                    <td><button>8</button></td>
                    <td><button>9</button></td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                     <td>&nbsp;</td>
                    <td><button>0</button></td>
                    <td>&nbsp;</td>
                    <td><button data-bind='click: clear'>C</button></td>
                    <td><button data-bind='event:{click: calculate}'>=</button></td>
                </tr>
            </table>
        </td>
    </tr>
</table>

JavaScript

var CalculatorViewModel = function() {
    this.currentOperand = ko.observable("0");
    var firstOperand;
    var secondOperand;
    var operatorSelected;

    this.numberClick = function(number){
        alert('inside numberclick');
        alert(number.value);
        alert(this.currentOperand());
        this.currentOperand(this.currentOperand() + number);
        alert(this.currentOperand());
        
    };
    
    this.clear = function() {        
        this.currentOperand('');
        firstOperand = 0;
        secondOperand = 0;
        operatorSelected = '';
    }
    
    this.add = function() {
        firstOperand = this.currentOperand();
        operatorSelected = "+";
    };

    this.subtract = function() {
        firstOperand = this.currentOperand();
        operatorSelected = "-";
    };

    this.calculate = function() {
        alert('inside calculate');
        secondOperand = this.currentOperand();

        switch (operatorSelected) {
        case "+":
            this.currentOperand(firstOperand + secondOperand);
            break;

        case "-":
            this.currentOperand(firstOperand - secondOperand);
            break;
        }

    }
}
        
ko.applyBindings(new CalculatorViewModel());