Passa al contingut principal

Calculator using knockout.js

Calculator using knockout.js

Calculator using knockout.js



Today I’d like to share our first tutorial about Knockout.js. This is the one of popular javascript libraries which let us use Model-View-View Model (MVVM) pattern in our web applications. Knockout is an extendable and crossbrowser framework, this is a new look at building of javascript applications. The main idea is separation of logic and presentation. We have to create a model and bind it with presentation. To link View and ViewModel is used data-attributes of HTML5. As a demonstration – I prepared a Math calculator with this new library (knockout.js).



Live Demo

download in package



If you are ready – let’s start!




Step 1. HTML


This is our presentation side (html markup):



<script src="js/knockout-2.2.0.js"></script>
<div class="calculator">
<p>Math Calculator</p>
<h3 data-bind="text: commandline"></h3>
<div data-bind="foreach: numbers" class="numbers">
<button data-bind="value: val, text: val, click: $parent.addNumber"></button>
</div>
<div data-bind="foreach: commands" class="commands">
<button data-bind="value: command, text: command, click: $parent.addCommand, disable: $parent.hasNumbers"></button>
</div>
<button data-bind="click: doCalculate" style="width: 330px">=</button>
</div>
<script src="js/main.js"></script>

Our calculator consists of ten digit buttons (numbers) and nine commands. I’m going to use two sets: digits and commands (to generate buttons) instead adding all of them manually. Now, we have to review and understand the Model to understand how it works.


Step 2. JS


js/main.js



var CalculatorModel = function() {
var self = this;

// array of possible commands
self.commands = [
{command: ' + '},
{command: ' - '},
{command: ' * '},
{command: ' / '},
{command: 'sin', action: 'Math.sin(__param__)'},
{command: 'cos', action: 'Math.cos(__param__)'},
{command: 'tan', action: 'Math.tan(__param__)'},
{command: 'ln', action: 'Math.log(__param__)'},
{command: 'log', action: 'Math.log(__param__) / Math.log(10)'},
];

// array of possible numbers
self.numbers = [
{val: 1},
{val: 2},
{val: 3},
{val: 4},
{val: 5},
{val: 6},
{val: 7},
{val: 8},
{val: 9},
{val: 0},
];

// result command line
self.commandline = ko.observable('');

// last used command
self.lastCommand = ko.observable('');

// do we need cleanup?
self.needCleanup = ko.observable(false);

// add a number function
self.addNumber = function(e) {
if (self.needCleanup()) {
self.commandline('');
self.needCleanup(false);
}

// we don't need to add leading zeros
if (this.val == 0 && self.commandline() == '') {
return;
}
self.commandline(self.commandline() + this.val);
};

// add a command function
self.addCommand = function(e) {
if (e.action && self.commandline()) { // in case of commands which don't require a second value - we have to calculate a value
var newCommand = e.action.replace('__param__', self.commandline());
self.commandline(eval(newCommand));
self.needCleanup(true);
}

if (self.lastCommand() == '') { // put a command into command line
if (! e.action) {
self.commandline(self.commandline() + e.command);
}
self.lastCommand(e.command);
}
};

// calculation
self.doCalculate = function(e) {
self.commandline(eval(self.commandline()));

if (self.lastCommand() != '') {
self.lastCommand('');
}
self.needCleanup(true);
};

// disable buttons if we haven't added any numbers yet
self.hasNumbers = ko.computed(function() {
return self.commandline() == '';
}, self);
};

ko.applyBindings(new CalculatorModel());

This is our Calculator Model, in the beginning – I defined two arrays (commands and numbers). They contain all the possible digits and action (for our buttons). As you know, for usual commands (like adding, subtracting, multiplying and dividing) we have to use two numbers to operate with, in case of other functions (sin, cos, tan etc) – only one. I had to put a real javascript commands as values of ‘action’ field. The main idea of this calculator is to compose a string (of math actions) to evaluate. In case if we need to sum two numbers (as example 2 and 3) we have to save ’2+3′ as command. And when we click ‘=’ button – we have to evaluate this command and display a result. And, now we can use foreach (in the Presentation) to display all the buttons (with digits and actions):



<div data-bind="foreach: numbers" class="numbers">
<button data-bind="value: val, text: val, click: $parent.addNumber"></button>
</div>
<div data-bind="foreach: commands" class="commands">
<button data-bind="value: command, text: command, click: $parent.addCommand, disable: $parent.hasNumbers"></button>
</div>

As you see – we can use variables (and even functions) of our Model in the Presentation (DOM model). When we click on the digit buttons – the script adds digits, when we click on the commands – the script uses these commands to calculate a result. I hope that you will be able to understand rest logic of our application.


Step 2. JS


Finally, I would like to publish CSS styles of our calculator:


css/main.css



.calculator {
/*css3 gradient*/
background: #e2e2e2; /* Old browsers */
background: -moz-linear-gradient(top, #e2e2e2 0%, #dbdbdb 50%, #d1d1d1 51%, #fefefe 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e2e2e2), color-stop(50%,#dbdbdb), color-stop(51%,#d1d1d1), color-stop(100%,#fefefe)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* IE10+ */
background: linear-gradient(to bottom, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e2e2e2', endColorstr='#fefefe',GradientType=0 ); /* IE6-9 */

display: block;
margin: 20px auto 0;
padding: 20px;
position: relative;
width: 340px;

/*css3 border radius*/
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;

/*css3 shadow*/
-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
}
.calculator button {
background-color: #eeeeee;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eeeeee), color-stop(100%, #cccccc));
background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);
background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
background-image: linear-gradient(top, #eeeeee, #cccccc);
border: 1px solid #ccc;
border-bottom: 1px solid #bbb;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
color: #333;
font: bold 11px/1 "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
margin: 5px;
padding: 8px 0;
text-align: center;
text-shadow: 0 1px 0 #eee;
width: 100px;
}
.calculator button:hover {
background-color: #dddddd;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #dddddd), color-stop(100%, #bbbbbb));
background-image: -webkit-linear-gradient(top, #dddddd, #bbbbbb);
background-image: -moz-linear-gradient(top, #dddddd, #bbbbbb);
background-image: -ms-linear-gradient(top, #dddddd, #bbbbbb);
background-image: -o-linear-gradient(top, #dddddd, #bbbbbb);
background-image: linear-gradient(top, #dddddd, #bbbbbb);
border: 1px solid #bbb;
border-bottom: 1px solid #999;
cursor: pointer;
text-shadow: 0 1px 0 #ddd;
}
.calculator button:active {
border: 1px solid #aaa;
border-bottom: 1px solid #888;
-webkit-box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
box-shadow: inset 0 0 5px 2px #aaaaaa, 0 1px 0 0 #eeeeee;
}
.calculator p {
margin-bottom: 15px;
text-align: center;
}
.calculator h3 {
background-color: rgba(255, 255, 255, 0.4);
height: 23px;
margin-bottom: 10px;
padding: 8px;
text-align: right;
}
.calculator div {
background-color: rgba(255, 255, 255, 0.4);
margin-bottom: 10px;

/*css3 border radius*/
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}



Live Demo

download in package



Conclusion


This is all for today, we have just finished developing the math calculator. If you need – it is pretty easy to expand functionality of this calculator, all you need is to expand our Model (and add own action buttons here). See you next time, good luck!






via Script Tutorials»Script Tutorials | Web Developer Tutorials | HTML5 and CSS3 Tutorials http://www.script-tutorials.com/calculator-using-knockout-js/

Comentaris

Entrades populars d'aquest blog

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

El meu editor de codi preferit el 2024, que això ja se sap que va canviant 😄

Visual Code Visual Code és un editor de codi font lleuger, però potent que s’executa al teu escriptori i està disponible per a Windows, macOS i Linux. Compta amb suport integrat per a JavaScript, TypeScript i Node.js i té un ric ecosistema d’extensions per a altres llenguatges i entorns d’execució (com C++, C#, Java, Python, PHP, Go, .NET).  És una eina ideal per a desenvolupar i depurar aplicacions web i en el núvol. Per què Visual Code? Visual Code té molts avantatges com a editor de codi font, com per exemple: És gratuït, ràpid i fàcil d’instal·lar i actualitzar. Té un ampli ecosistema d’extensions que et permeten afegir funcionalitats i personalitzar la teva experiència de desenvolupament. Té un suport integrat per a molts llenguatges i entorns d’execució, i et permet depurar i executar el teu codi des del mateix editor. Té una interfície senzilla i elegant, amb diferents temes i modes de visualització. Té un sistema de sincronització de configuracions que et permet guardar les...

Las Mejores Aplicaciones Gratis para iPad de 2012

Las Mejores Aplicaciones Gratis para iPad de 2012 : ¿No tienes ni un duro? No te preocupes, pues hoy os traemos una extensa selección de las mejores apps gratuitas que puedes conseguir en la App Store para que llenes tu iPad de calidad, sin gastar nada de nada.   ¿Estás buscando juegos o apps gratis para tu iPad? En la App Store hay más de 500,000 apps y juegos, y una gran cantidad de ellos está disponible de forma totalmente gratuita. Aquí vamos con la selección de las mejores Apps gratis para iPad (todos los modelos), organizada por categoría. ¿Estás preparado? Las Mejores Apps Gratis de Redes Sociales para iPad Nombre Facebook Gratis Categoría Redes sociales Facebook es la red social más famosa del mundo , con casi mil millones de usuarios. Su app para iPad ha tardado, pero aquí está. Nombre Twitter Gratis Categoría Redes sociales Twitter es la red de microblogging por excelencia. La forma más rápida y directa de informar y mantenerse informado de las cosa...