Search code examples
titaniumcontrollerstitanium-alloy

titanium alloy: calling controller function from another controller


Using SDK 3.2.0

I have a index controller that defines a function to set Android Menus. I want to call that function from a variety of controllers that are nested loaded throughout the App. Code:

//index.js
exports.setMenus = function(enabled) {
        var activity = $.index.getActivity();
        activity.onCreateOptionsMenu = function(e){
           /...
        };
        activity.onPrepareOptionsMenu = function(e) {
           /...
        };
        activity.invalidateOptionsMenu();
}; 
Alloy.Globals.Index = $;

Then, way after, inside home controller, I try this:

function startRefresh() {
    //...
    Alloy.Globals.Index.setMenus(true); 
}
$.on('focus', startRefresh);

Got the following error message:

[ERROR] :  TiExceptionHandler: (main) [1,40482] - In alloy/controllers/home.js:8,29
[ERROR] :  TiExceptionHandler: (main) [0,40482] - Message: Uncaught TypeError: Obje
ct #<Controller> has no method 'setMenus'
[ERROR] :  TiExceptionHandler: (main) [0,40482] - Source:         Alloy.Globals.Ind
ex.setMenus(true);

I have followed instructions from this answer. I want to use exports because the controllers calling setMenus are not children of index, they are deeper nested. I mean, I'm trying to avoid passing arguments between controllers.

Why setMenus is not been exported?

WHAT WORKED:

//index.js
exports.setMenus = function(enabled) {
        var activity = $.index.getActivity();
        //...
}; 
Alloy.Globals.setMenus = setMenus;

and

//home.js
function startRefresh() {
    //...
    Alloy.Globals.setMenus(true); 
}
$.on('focus', startRefresh);

Solution

  • If you want to call a function from a variety of controllers then you can write that function in alloy.js for ex:

    Alloy.Globals.someGlobalFunction = function(){ alert("Hello"); };

    and now you cal call the function anywhere like Alloy.Globals.someGlobalFunction();