Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

global functions

how to create global function so i cant use in all sub windows ?
for example

var doit=function(parm1){

    //// mycode .........

}

and then us it anywhere .
should i put in the app.js or to include it in every page ?
thanks !.

— asked August 3rd 2010 by gmb Bi
  • functions
0 Comments

7 Answers

  • Hi there,

    Use an include at the top of your files…

    In this example I will show you how I create a persistence module for retrieving a list of brands from a database.

    create your include file (in my case dbfunctions.js) with your various functions in it.

    /*************************************************************
    dbfunctions.js - database functions
    v 0.1
    **************************************************************/
    var db = (function() {
    var api     = {};
    var conn     = Titanium.Database.open('mydb');
    
    api.all_brand_names_picker = function() {
        if (debug){  Ti.API.info('api.all_brand_names'); }
        var results = [];
        var resultSet = conn.execute('select * from brands');
        while ( resultSet.isValidRow()) {
            results.push({
                title:        resultSet.fieldByName('brand_name')
            });
            resultSet.next();
        }
        resultSet.close();
        return results;
        };
    
    return api;
    }
    

    Then in your javascript files include the persistent functions…

    Titanium.include('dbfunctions.js');
    

    and call the functions as required

    var filterPicker = Titanium.UI.createPicker({ 
        top:    140, 
        type:    Titanium.UI.PICKER_TYPE_PLAIN 
    });
    
    filterPicker.add(db.all_brand_names_picker());
    

    Hope this helps.

    — answered August 3rd 2010 by Gregor Munro
    permalink
    1 Comment
    • I cannot get this to work as is. The only way I can get it to work is to instantiate db before calling the all_brand_names_picker() method, like this:

      var dbInst = new db();
      filterPicker.add(dbInst.all_brand_names_picker());
      

      — commented December 29th 2010 by David Knell
  • Tamas' approach won't work if you open your sub-windows in separate contexts (if they're in separate .js files).

    One approach would be creating a separate javascript file that holds your global functions / objects and then include this file wherever you need it.

    For example, if your global functions are in globals.js, you can include this in other files with Titanium.include('globals.js'). Then you can call your functions normally.

    Btw, the include paths are relative to your Resources folder.

    — answered August 3rd 2010 by Goran Skledar
    permalink
    0 Comments
  • what about storing global values

    like when you start your app and get info from server which you don't like to download every time

    how to put this data (array) in place that all window can see and get
    last time i putted them inside the tabgroup however tabGroup start to act crazy

    — answered August 10th 2010 by gmb Bi
    permalink
    0 Comments
  • what about storing global values

    like when you start your app and get info from server which you don't like to download every time

    how to put this data (array) in place that all window can see and get
    last time i putted them inside the tabgroup however tabGroup start to act crazy

    — answered August 10th 2010 by gmb Bi
    permalink
    0 Comments
  • I imagine that this is a big no-no, but it seems to work. By adding your own methods to the Titanium.App object, you can create globally accessible functions, usable from anywhere in the app. Take this example of an application-wide API wrapper for a remote service.

    In app.js:

    Titanium.App.apiRequest = function(params) {
        var apiKey = Titanium.App.Properties.getString("apiKey");
        var xhr = Titanium.Network.createHTTPClient();
        xhr.onload = function() {
            if (params.hasOwnProperty('callback') && typeof params.callback == 'function') {
                params.callback(JSON.parse(this.responseText));
            }
        };
        xhr.onerror = function() {
            Ti.API.error(this.status + ' - ' + this.statusText);
        };
        var thisUrl = Titanium.App.Properties.getString("apiURL")+"/"+params.action;
    
        // include any URL variables (for GET requests)
        if (params.hasOwnProperty('params') && typeof params.params == 'object') {
            var c = 0;
            for (param in params.params) {
                thisUrl += (c==0) ? "?" : "&";
                thisUrl += param + "=" + params.params[param];
                c++;
            }
        }
    
        // handle the HTTP request type
        xhr.open(params.hasOwnProperty('method') ? params.method : 'GET', thisUrl);
    
        // create the Authorization header
        var authstr = 'Basic '+Titanium.Utils.base64encode(apiKey+':x');
        xhr.setRequestHeader('Authorization', authstr);
    
        // include any JSON data that is provided
        if (params.hasOwnProperty('data')) {
            xhr.send(JSON.stringify(params.data));
        } else {
            xhr.send();
        }
    }
    

    And then from within another context, anywhere in your app, you can call:

    Titanium.App.apiRequest({
        action:  'projects',
        callback: function(resp) {
            ...
        }
    });
    

    Remember, this is generally bad advice! with each "custom" method you add to Titanium.App, you are "polluting" the namespace. If you do use this technique take care not to override any important methods!

    — answered November 30th 2010 by Jordan Titanium
    permalink
    1 Comment
    • Strangely this seems to work for iPhone but not Android. Very odd.

      — commented December 1st 2010 by Jordan Titanium
  • In app.js should do the trick.

    — answered August 3rd 2010 by Dan Tamas
    permalink
    0 Comments
  • i found that putting all functions on app.js wont let me use theme in sub windows however using Groan way solve it by including the function

    and also i found new way

    1- create your function

    var doit=function(parm1){
    
    
    }
    

    2- assaign this to global object i found the tabGroup good one

    var tabGroup = Titanium.UI.createTabGroup({
    myVar:"global var",
    doit:doit
    });
    

    3- in any sub window you can use it by calling

    var win = Titanium.UI.currentWindow;
    win.tabGroup.doit();
    
    — answered August 3rd 2010 by gmb Bi
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.