Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Titanium Alloy: Accessing UI from different controllers?

I seem to be having trouble updating objects in Titanium Appcelerator Alloy,

I basically want to be able to add a table row to a table that is in a different controller/view that i am currently in..... hopefully the below will better describe this :s

basket.xml

<Alloy>
    <Window id="basketWindow" class="container">
        <TableView id="basketTable" />
        <Button id="addItemButton" onClick="addItem">Add Item</Button>
    </Window>
</Alloy>

basket.js

function addItem()
{
    var itemList = Alloy.createController('item_list');

    itemList.getView().open();
}

item_list.xml

<Alloy>
    <Window id="itemListWindow" class="container">
        <TableView id="itemListTable">
            <TableViewRow id="item1" className="item" onClick="addItemToBasket">
                Test Item
            </TableViewRow>
        </TableView>
    </Window>
</Alloy>

item_list.js

function addItemToBasket()
{
    var row = Ti.UI.createTableViewRow({title: 'Test Item'});

    // Here i would ideally want to put something like $.basketTable.append(row);
    // But nothing happens, im guessing it cant find $.basketTable as its in a different controller?

}

Does anyone know away around this?

Thanks for reading :)

like image 698
David Avatar asked Apr 17 '13 14:04

David


1 Answers

One simple, easy solution is to just trigger an app wide event when you add an item to the basket:

function addItemToBasket() {
    Ti.App.fireEvent("app:itemAddedToBasket", {
       title : "Test Item", 
       otherAttribute : "Value"
    });
}

Then listen for the event in the basket controller somewhere, and add the table row:

// inside basket.js
Ti.App.addEventListener("app:itemAddedToBasket", function(e) {
    // object 'e' has all the row information we need to create the row
    var row = Ti.UI.createTableViewRow({
        title: e.title, 
        otherAttribute: e.otherAttribute
    });
    // Now append it to the table
    $.basketTable.append(row);
});
like image 68
Josiah Hester Avatar answered Oct 30 '22 15:10

Josiah Hester