Skip to content

Instantly share code, notes, and snippets.

@adamtarmstrong
Last active April 11, 2018 08:55
Show Gist options
  • Save adamtarmstrong/a85bb70ed2e5ebdfe6aa9354e28412b0 to your computer and use it in GitHub Desktop.
Save adamtarmstrong/a85bb70ed2e5ebdfe6aa9354e28412b0 to your computer and use it in GitHub Desktop.
AppC: Using RESTe + local sqlite DB
//alloy.js
require("sqlite_reste_config");
var localDB = require('sqlite_db');
localDB.initDB();
//sqlite_reste_config.js
Alloy.Globals.reste = require("reste");
Alloy.Globals.sqlDB = new Alloy.Globals.reste();
Alloy.Globals.sqlDB.createCollection("addOns", [] );
//sqlite_db.js
exports.initDB = function(){
var db = Ti.Database.open('myDB');
//add ons Table and Collection
db.execute('CREATE TABLE IF NOT EXISTS addons(id INTEGER PRIMARY KEY, title TEXT, date TEXT, price REAL, cakeprojectid INTEGER);');
Alloy.Globals.sqlDB.createCollection("addOns", [] );
db.close();
};
exports.create_NewAddOn = function(addonTitle,addonDate,addonPrice,cakeProjectID){
var db = Ti.Database.open('myDB');
db.execute('INSERT INTO addons (title,date,price,cakeprojectid) VALUES (?,?,?,?)', addonTitle, addonDate, addonPrice, cakeProjectID);
db.close();
_get_AddOns(cakeProjectID);
};
function _get_AddOns(cakeProjectID){
var db = Ti.Database.open('myDB');
var addonResults = [];
var result = db.execute('SELECT * FROM addons WHERE cakeprojectid = ? ORDER BY date ASC', cakeProjectID);
var addonResultCount = result.getRowCount();
if (addonResultCount > 0) {
while (result.isValidRow()) {
addonResults.push({
id: result.fieldByName('id'),
title: result.fieldByName('title'),
date: result.fieldByName('date'),
price: result.fieldByName('price'),
cakeprojectid: result.fieldByName('cakeprojectid')
});
result.next();
}
}
db.close();
Alloy.Globals.sqlDB.createCollection("addOns", addonResults );
Alloy.Collections.addOns.trigger("change");
}
exports.get_AddOns = _get_AddOns;
//VIEW
<ListSection dataCollection="addOns" ....
//CONTROLLER
//onLoad, you only need this to 'get' the collection
localDB.get_AddOns(cakeProjectID);
//Also....if you wanted to add an item - this would execute the sql function to add and in turn also updates the collection
localDB.create_NewAddOn(addonTitle,moment().format(),addonCost,cakeProjectID);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment