Search code examples
titaniumappceleratorappcelerator-mobile

Using Global Function in Titanium


I am making Titanium mobile project where I want to make one global function which I can use throughout the application. For that I have created other .JS file where I have defined the function and I am including that .JS file where I need to use this function and I am successfully able to call the function.

But My question is :

Can I create new Window in that function? As I have added one Label and one MapView in that window but it is not showing, while at the start of function I have added alert('FunctionCalled'), it is showing me alert but not showing me the label I have added in the window.

So anybody can help me to find out whether we can open window through function. If yes then any sample example, so that I can find out what mistake I am making.

Thanks,

Rakesh Gondaliya


Solution

  • you approach CAN work but is not a best practice, you should create a global namespace, add the function to that namespace and then only include the file with the function once in app.js

    // apps.js
    var myApp = {};
    Ti.include('global.js','ui.js');
    
    myApp.ui.openMainWindow();
    

    then we create a seperate file for our ui functions

    //ui.js
    (function(){
    
    var ui = {};
    
    ui.openMainWindow = function() {
        // do open window stuff
    
        // call global function
        myApp.global.globalFunction1();
    }
    
    myApp.ui = ui;
    })();
    

    here is where we create our global functions, we will not have to include the file everywhere since we are adding it to our global namespace

    //global.js
    (function(){
    
    var global = {};
    
    global.globalFunction1 = function() {
        // do super global stuff
    }
    
    myApp.global = global;
    })();
    

    this is a simple outline of how it can be implemented, I have a complete code listing on my blog