Skip to content

Commit

Permalink
figure 5-5
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanstark committed Jan 2, 2012
1 parent 22fbb43 commit a0b82dc
Showing 1 changed file with 66 additions and 2 deletions.
68 changes: 66 additions & 2 deletions ch05/kilo.js
@@ -1,16 +1,35 @@
var jQT = $.jQTouch({
icon: 'kilo.png'
});
var db;
$(document).ready(function(){
$('#createEntry form').submit(createEntry);
$('#settings form').submit(saveSettings);
$('#settings').bind('pageAnimationStart', loadSettings);
$('#dates li a').click(function(){
var dayOffset = parseInt(this.id);
var dayOffset = this.id;
var date = new Date();
date.setDate(date.getDate() - dayOffset);
sessionStorage.currentDate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
sessionStorage.currentDate = date.getMonth() + 1 + '/' +
date.getDate() + '/' +
date.getFullYear();
refreshEntries();
});
var shortName = 'Kilo';
var version = '1.0';
var displayName = 'Kilo';
var maxSize = 65536;
db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(
function(transaction) {
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS entries ' +
' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
' date DATE NOT NULL, food TEXT NOT NULL, ' +
' calories INTEGER NOT NULL );'
);
}
);
});
function saveSettings() {
localStorage.age = $('#age').val();
Expand All @@ -36,4 +55,49 @@ function loadSettings() {
function refreshEntries() {
var currentDate = sessionStorage.currentDate;
$('#date h1').text(currentDate);
$('#date ul li:gt(0)').remove();
db.transaction(
function(transaction) {
transaction.executeSql(
'SELECT * FROM entries WHERE date = ? ORDER BY food;',
[currentDate],
function (transaction, result) {
for (var i=0; i < result.rows.length; i++) {
var row = result.rows.item(i);
var newEntryRow = $('#entryTemplate').clone();
newEntryRow.removeAttr('id');
newEntryRow.removeAttr('style');
newEntryRow.data('entryId', row.id);
newEntryRow.appendTo('#date ul');
newEntryRow.find('.label').text(row.food);
newEntryRow.find('.calories').text(row.calories);
}
},
errorHandler
);
}
);
}
function createEntry() {
var date = sessionStorage.currentDate;
var calories = $('#calories').val();
var food = $('#food').val();
db.transaction(
function(transaction) {
transaction.executeSql(
'INSERT INTO entries (date, calories, food) VALUES (?, ?, ?);',
[date, calories, food],
function(){
refreshEntries();
jQT.goBack();
},
errorHandler
);
}
);
return false;
}
function errorHandler(transaction, error) {
alert('Oops. Error was '+error.message+' (Code '+error.code+')');
return true;
}

0 comments on commit a0b82dc

Please sign in to comment.