Search code examples
titanium

how to implement function from another .js file in Titanium


how to use functions/methods from another .js file in titanium?

eg Utils.js

var db = Titanium.Database.open('myinfodb');
function addIntoDb(name) {
    db.execute('INSERT INTO info (name) VALUES(?)', name);
    Ti.Ti.API.info(name+' Added to db');
}

function getFromDb() {
    var holddatavar = db.execute('SELECT name FROM info');
    return holddatavar;
}

db.close();

how to use this in my current js file?


Solution

  • db.js

    // creates your database if necessary
    var db = Titanium.Database.open('myinfodb');
    db.execute('CREATE TABLE IF NOT EXISTS [info] (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
    db.close();
    
    var addIntoDb = function(name) {
        var db = Titanium.Database.open('myinfodb');
        db.execute('INSERT INTO info (name) VALUES(?)', name);
        Ti.Ti.API.info(name+' Added to db');
        db.close();
    }
    exports.addIntoDb = addIntoDb; // <=== This exposes the function to another file
    
    // This function would remain accessible only to the file because we didn't export the function
    function getFromDb() {
        var holddatavar = db.execute('SELECT name FROM info');
        return holddatavar;
    }
    

    Then you would use it in other JavaScript files to access it like so:

    var db = require('/mypath/db'); // NO .js extension on this
    db.addIntoDb('Pravin');