Exchange rate example – Full example

Let’s construct the entire app.

 1<div data-role='page' id='root'>
 2  <div data-role='header'>
 3    <h1>Exchange Rate</h1>
 4    <a class='ui-btn-right' data-role='button' data-transition='slide' href='#about'>關於</a>
 5  </div>
 6  <div data-role='content'>
 7    <label for='cny-input'>人民幣</label>
 8    <input type='number' id='cny-input' placeholder='0.00'>
 9    <input type="submit" id='submit' value="Show me the MOP">
10    <p id="result">CNY $0.00 = MOP $0.00</p>
11  </div>
12</div>

Different between number and text in input.

1<input type='text' placeholder='0.00'>
2<input type='number' placeholder='0.00'>

Getting the latest exchange rates from web service.

 1// Model
 2;(function($){
 3  var app = this.app || (this.app={});
 4
 5  var key = '<API_KEY_HERE>';
 6  var url = 'http://openexchangerates.org/api/latest.json?app_id=' + key + '&callback=?';
 7
 8  $.getJSON(url, function(data){
 9    // console.log(data); // print the JSON response.
10    app.rates = data.rates;
11
12  });
13}).call(this, jQuery);

Our previously defined Exchange function, with the rates variable put into app scope now.

 1// Exchange module (part of the Model)
 2;(function(){
 3  var app = this.app || (this.app={});
 4
 5  function Exchange(value, srcCurrency) {
 6    var srcPerUsd = app.rates[srcCurrency.toUpperCase()];
 7    var usdPerSrc = 1 / srcPerUsd;
 8
 9    return {
10      to: function(targetCurrency) {
11        var targetPerUsd = app.rates[targetCurrency.toUpperCase()];
12        var srcPerTarget = usdPerSrc * targetPerUsd;
13        return value * srcPerTarget;
14      }
15    };
16  }
17
18  app.Exchange = Exchange;
19}).call(this);

As usual, we have a dedicated module for querying and changing the interface.

 1// View
 2;(function($){
 3  var app = this.app || (this.app={});
 4
 5  var result = $('#result');
 6
 7  app.view = {}
 8  app.view.button = $('#submit');
 9  app.view.input = $('#cny-input');
10
11  app.view.updateResult = function(cny, mop) {
12    result.html('CNY $' + cny.toFixed(2) +' = MOP $' + mop.toFixed(2));
13  }
14
15}).call(this, jQuery);

Finally, we have all the ingredients prepared. Here comes the final logic to glue them together.

1;(function(){
2
3  app.view.button.on('click', function(){
4    var cny = app.view.input.val() * 1;
5    var mop = app.Exchange(cny, 'CNY').to('MOP');
6    app.view.updateResult(cny, mop);
7  });
8}).call(this);

Finally, we created the following exchange rate app.

Exchange rate screenshot

What’s next? We’re going to take a look at “Challenges”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content