Alex McDaid
Alex McDaid

Reputation: 269

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

Upvotes: 3

Views: 2430

Answers (2)

Juanu
Juanu

Reputation: 548

That's one way. The other (which IMHO is better because you avoid Global) is simpler. You can access the tab just by doing:

function setup(){
    //This DOES work.
    // Just keep in mind that you must use the tab index corresponding to your tab.
    // Also, If your view actually uses a window and the tab is on your TabGroup view,
    // you should do $.tabGroup.tabs[1].window.
    var view = $.tabGroup.tabs[1]; 
    view.changeBackground('blue');
    $.tabGroup.setActiveTab(1);
}

Upvotes: 0

Alex McDaid
Alex McDaid

Reputation: 269

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

Upvotes: 2

Related Questions