Search code examples
javascripttitaniumtitanium-mobile

Titanium Alloy, Require Controller


I have a project build in titanium SDK 3.02 using the Alloy framework. Its a tabbed application, and I want to change the view of tab2 from a button inside tab1

tab1.xml

...
    <Button id="button" onClick="setup">
...

tab1.js

function setup(){
    //this doesn't work
    var view = Alloy.createController('tab2');
    view.changeBackground('blue');
    $.tabGroup.setActiveTab(1);
}

tab2.xml

...
    <View id="view" backgroundColor="red">
...

tab2.js

...
    exports.changeBackground = function(color){
        $.view.backgroundColor = color;
        //this runs eg
        Ti.API.info('function running');
    }

I understand why this wont work. I am creating a new instance of the controller which is never added to a view. But i want to access the existing controller. I have tried

var view = require('tab2');
view.changeBackground('blue');

But this gives me a 'module not found error'. I hope this makes sense

Thanks


Solution

  • Solved it

    Setting the function in tab2 as an Alloy.Global did the trick.

    tab1.xml

    ...
        <Button id="button" onClick="setup">
    ...
    

    tab1.js

    function setup(){
        var changeBackgroundColor = Alloy.Globals.changeBackgroundColor;
        changeBackgroundColor('blue');
        $.tabGroup.setActiveTab(1);
    }
    

    tab2.xml

    ...
        var changeBackground = function(color){
            $.view.backgroundColor = color;
        }
        Alloy.Global.changeBackGroundColor = changeBackground;
    ...