titanium alloy: calling controller function from another controller

余生颓废 提交于 2019-12-10 11:34:25

问题


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);

回答1:


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();



来源:https://stackoverflow.com/questions/23364151/titanium-alloy-calling-controller-function-from-another-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!